推荐系统初始化

This commit is contained in:
2023-05-09 17:53:58 +08:00
commit 9f8c374ac2
406 changed files with 68905 additions and 0 deletions

13
api/.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
/.factorypath
/.project
/.apt_generated
/.settings
/target
/.classpath
@logs_path@
/logs
.idea
*.iml
!/src/main/resources/config/spring-redisson.yaml
!/src/main/resources/application.yml
/doc

11
api/Dockerfile Normal file
View File

@@ -0,0 +1,11 @@
FROM docker.io/openjdk:8u151-slim
MAINTAINER saber "saber.zhicheng@foxmail.com"
EXPOSE 10010
RUN mkdir -p /opt/app/java
COPY target/application.jar /opt/app/java/application.jar
RUN mkdir -p /etc/java
COPY target/classes/config.properties /etc/java/application.conf
CMD ["java", "-XX:+UseParNewGC", "-XX:+CMSParallelRemarkEnabled", "-XX:ParallelGCThreads=10", "-XX:+CMSScavengeBeforeRemark", "-XX:ParallelCMSThreads=10", "-XX:+CMSPermGenSweepingEnabled", "-XX:+CMSClassUnloadingEnabled", "-Xmx4096m", "-Xms512m", "-XX:PermSize=512m", "-XX:MaxPermSize=4096m", "-Dspring.application.name=syria-api", "-DCONFIG_FILE=file:/etc/java/application.conf", "-Dfile.encoding=UTF8", "-Duser.timezone=GMT+08", "-jar", "/opt/app/java/application.jar"]

15
api/apidoc.json Normal file
View File

@@ -0,0 +1,15 @@
{
"name": "SpringBootAPIs",
"version": "1.0.0",
"description": "接口文档",
"title": "SpringBootAPIs",
"url": "http://1.116.164.215/api",
"header": {
"title": "文档说明",
"filename": "header.md"
},
"footer": {
"title": "文档结尾",
"filename": "footer.md"
}
}

2
api/footer.md Normal file
View File

@@ -0,0 +1,2 @@
### 感谢查阅
以上文档仅供参考,如有疑问或实际接口与文档不符请联系相关负责人。

1
api/header.md Normal file
View File

@@ -0,0 +1 @@
本文档仅供内部查阅,谢绝公开,感谢大家配合。

4
api/init_doc.bat Normal file
View File

@@ -0,0 +1,4 @@
@echo off
apidoc.cmd -i src/ -o doc/
pause

3
api/package-lock.json generated Normal file
View File

@@ -0,0 +1,3 @@
{
"lockfileVersion": 1
}

444
api/pom.xml Normal file
View File

@@ -0,0 +1,444 @@
<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 http://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>2.3.0.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.wx</groupId>
<artifactId>recom-gorse-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>application</name>
<description>后端API</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<fastjson.version>1.2.73</fastjson.version>
<druid.version>1.1.6</druid.version>
<mybatis.plus.version>3.1.2</mybatis.plus.version>
<hutool.version>5.8.4</hutool.version>
<maven-jar-plugin.version>3.0.0</maven-jar-plugin.version>
<jwt.version>0.10.7</jwt.version>
<neo4j.ogm.version>3.2.1</neo4j.ogm.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- redis -->
<!-- <dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.13.1</version>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis.plus.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.0-jre</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--模板生成引擎 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<!--jwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.0</version>
</dependency> -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>net.sourceforge.javacsv</groupId>
<artifactId>javacsv</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
<!--腾讯云依赖包-->
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>cos-sts-java</artifactId>
<version>3.0.6</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.19</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.37</version><!-- 注:此处仅为示例版本号,请访问 https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java 获取最新版本号并替换 -->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>com.carrotsearch</groupId>
<artifactId>hppc</artifactId>
<version>0.8.2</version>
</dependency>
<dependency>
<groupId>com.vesoft</groupId>
<artifactId>client</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>recom-gorse</finalName>
<!--需要移除的模块 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>static/css/**</exclude>
<exclude>static/data/**</exclude>
<exclude>static/docs/**</exclude>
<exclude>static/fonts/**</exclude>
<exclude>static/img/**</exclude>
<exclude>static/plugins/**</exclude>
<exclude>static/view/**</exclude>
</excludes>
</resource>
</resources>
<plugins>
<!--最后一阶段再移除模板包-->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>_templates/**</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
<executions>
<execution>
<!--转移配置-->
<id>copy-application-yml</id>
<phase>deploy</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>config.properties</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-zips</id>
<phase>process-sources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<resources>
<!--拷贝点资源文件进jar-->
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<target>${java.version}</target>
<source>${java.version}</source>
<encoding>UTF-8</encoding>
<showWarnings>false</showWarnings>
<showDeprecation>false</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<mainClass>com.wx.application.Application</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<jdbc_url>jdbc:mysql://43.139.83.67:13306/dn_nebula</jdbc_url>
<db_username>root</db_username>
<db_password>AJuSP7F7VTRvm7rk</db_password>
<server_port>4026</server_port>
<logs_path>./logs/</logs_path>
<mybatis_plus_sql_show_format>true</mybatis_plus_sql_show_format>
<upload_graph_path>D:/nebulagraph/</upload_graph_path>
<zbx_path>D:/myReadCSV/southeastuniversity/jszb/</zbx_path>
<nebula_grap>true</nebula_grap>
<nebula_session_host>43.139.83.67</nebula_session_host>
<nebula_session_port>9669</nebula_session_port>
<nebula_session_username>root</nebula_session_username>
<nebula_session_password>123456</nebula_session_password>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
</project>

47
api/scripts/build_dev.sh Normal file
View File

@@ -0,0 +1,47 @@
#!/bin/bash
set -e
function parentDir()
{
local this_dir=`pwd`
local child_dir="$1"
dirname "$child_dir"
cd $this_dir
}
CURRENT_PATH=$(cd `dirname $0`; pwd)
DOCKER_IMAGE_NAME='syria/java-api:latest'
DOCKER_CONTAINER_NAME='syria-java-api'
DOCKER_CONTAINER_PORT=40010
workSpace=`parentDir "$CURRENT_PATH"`
echo '更新代码'
git pull
echo '工作空间'$workSpace
cd $workSpace
echo '开始打包'
mvn clean install -Dmaven.test.skip=true -Pdev
echo '开始构建docker镜像'
docker build -t $DOCKER_IMAGE_NAME .
count=`docker ps -a|grep $DOCKER_CONTAINER_NAME|wc -l`
if [ $count != 0 ];then
echo "准备移除容器 $DOCKER_CONTAINER_NAME ..."
docker rm -f $DOCKER_CONTAINER_NAME
else
echo "准备启动容器 $DOCKER_CONTAINER_NAME ..."
fi
docker run -d --restart always --net=host --add-host redis:127.0.0.1 --name $DOCKER_CONTAINER_NAME -v /var/log:/var/log -v /data/medical-follow:/data -v /etc/syria.conf:/etc/java/application.conf -it $DOCKER_IMAGE_NAME
docker images|grep -v REPOSITORY|grep none|awk '{print $3}'|xargs docker rmi
exit 0

View File

@@ -0,0 +1,72 @@
package com.wx.application;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* https://nebula-graph.com.cn/
* es 检查索引是否存在https://blog.csdn.net/qq_29631809/article/details/72172017
* es 创建索引https://blog.csdn.net/weixin_41507324/article/details/110862169
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.wx.application.*.mapper*"})
@ServletComponentScan(basePackages = {"com.wx.application.filter"})
@EnableScheduling
@EnableAsync
@PropertySource("${CONFIG_FILE:classpath:config.properties}")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
HttpMessageConverter<?> converter = jackson2HttpMessageConverter;
return new HttpMessageConverters(converter);
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI*表示全部允许在SpringMVC中如果设成*会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.addExposedHeader("Authorization");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");// 允许Get的请求方法
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}

View File

@@ -0,0 +1,180 @@
package com.wx.application.adapter.controller;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
//import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kaptcha.Kaptcha;
import com.google.common.collect.ImmutableMap;
import com.wx.application.adapter.dto.qo.RiskUserQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ErrorCodeEnum;
import com.wx.application.base.ResponseData;
import com.wx.application.constant.CONSTANT;
import com.wx.application.core.entity.RiskUser;
import com.wx.application.core.service.RiskUserService;
import com.wx.application.util.JwtUtils;
import com.wx.application.util.MD5Util;
import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequestMapping("/login")
@RestController("loginController")
public class LoginController extends BaseController {
@Autowired
RiskUserService riskUserService;
/*@Autowired
RedissonClient redissonClient;*/
@Autowired
private Kaptcha kaptcha;
/**
* @api {post} /login/captcha 获取验证码
* @apiName 获取验证码
* @apiGroup Login
* @apiParam {String} name 角色名称
* @apiParam {String} description 角色描述
* @apiParam {Boolean} isAssistant 是否为医生助理
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* }
* @apiDescription 向后端申请一个验证码
* 返回验证码的图片流,并且存入对应cookie_id
* 登录时传入对应cookie_id,用来验证对应错误码
* ---------------------------------
* @author : zj
* @since : Create in 2021-05-08
*/
@RequestMapping("captcha")
public void captcha() {
kaptcha.render();
}
/**
* 登录
*/
@PostMapping(value = "/user")
public ResponseData login(@RequestBody RiskUserQ loginQo) throws Exception {
// if(StringUtils.isBlank(loginQo.getCode())) {
// Map<String,String> data = new HashMap<>();
// data.put("msg", "验证码不能为空");
// return error(ErrorCodeEnum.USER_NOT_EXIST,data);
// }
//
// try {
// kaptcha.validate(loginQo.getCode());
// } catch (Exception e) {
// Map<String,String> data = new HashMap<>();
// data.put("msg", "验证码错误");
// return error(ErrorCodeEnum.USER_NOT_EXIST,data);
// }
/*if(StringUtils.isBlank(loginQo.getCode())) {
Map<String,String> data = new HashMap<>();
data.put("msg", "验证码不能为空");
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
}
try {
kaptcha.validate(loginQo.getCode());
} catch (Exception e) {
Map<String,String> data = new HashMap<>();
data.put("msg", "验证码错误");
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
}*/
/**
* 将密码改成md5加密查询
*/
Map<String,Object> mQ = new HashMap<>();
mQ.put("EQS_username", loginQo.getUsername());
mQ.put("EQS_password", MD5Util.MD5(loginQo.getPassword()));
mQ.put("EQS_type", loginQo.getType());
RiskUser riskUser = riskUserService.queryUnique(mQ);
if(riskUser != null) {
String token = JwtUtils.generateJwtToken(riskUser.getId(), CONSTANT.LOGIN_TYPE_ADMIN, riskUser);
RiskUser _riskUser = new RiskUser();
_riskUser.setRealname(riskUser.getRealname());
_riskUser.setUsername(riskUser.getUsername());
return success(ImmutableMap.<String, Object>builder()
.put("Authorization",token)
.put("user", _riskUser)
.build());
}
Map<String,String> data = new HashMap<>();
data.put("msg", "用户名密码错误");
return error(ErrorCodeEnum.USER_NOT_EXIST,data);
}
/**
* 解密用户敏感数据获取用户信息
*
* @param sessionKey 数据进行加密签名的密钥
* @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
* @param iv 加密算法的初始向量
* @return
*/
public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据
byte[] dataByte = Base64.decode(encryptedData);
// 加密秘钥
byte[] keyByte = Base64.decode(sessionKey);
// 偏移量
byte[] ivByte = Base64.decode(iv);
try {
// 如果密钥不足16位那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, "UTF-8");
return JSON.parseObject(result);
}
} catch (Exception e) {
}
return null;
}
}

View File

@@ -0,0 +1,16 @@
package com.wx.application.adapter.dto.qo;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class GraphTaskExecuteQ {
private Long taskId;
private List<GraphTaskFileExecuteQ> taskFiles;
}

View File

@@ -0,0 +1,37 @@
package com.wx.application.adapter.dto.qo;
import com.wx.application.nebula.graph.enums.IndexType;
import cn.hutool.json.JSONObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class GraphTaskFileExecuteQ {
/**
* GraphTaskFile
*/
private Long taskFileId;
/**
* 当前导入的是tag 还是 edge
*/
private IndexType type;
/**
* tag
* edge 名称
*/
private String name;
/**
* 对应关系
* {
* 属性名 文件header 名称
* name: "姓名"
* }
*/
private JSONObject correspond;
}

View File

@@ -0,0 +1,12 @@
package com.wx.application.adapter.dto.qo;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class OntologyQ {
private String label;
}

View File

@@ -0,0 +1,16 @@
package com.wx.application.adapter.dto.qo;
import javax.validation.constraints.NotNull;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class RemarkTaskRemoveOntologyQ {
@NotNull(message = "remarkId不能为空")
private Long remarkId;
private Long ontologyId;
}

View File

@@ -0,0 +1,59 @@
package com.wx.application.adapter.dto.qo;
public class RiskUserQ {
private String code;
private String username;
private String realname;
private String password;
/**
* font 前端登录
* admin 后端管理登录
*/
private String type;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}

View File

@@ -0,0 +1,65 @@
package com.wx.application.base;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;
/**
* @author zj
* @description : 控制器的基类,抽象方法,标准控制器有crud4个方法 ---------------------------------
* @since 2017-11-14
*/
public abstract class BaseController {
private static MessageSource messageSource;
@Autowired
public void setMessageSource(MessageSource messageSource) {
BaseController.messageSource = messageSource;
}
public static ResponseData success() {
return success(null);
}
public static ResponseData success(Object object) {
ResponseData rData = new ResponseData();
rData.setCode(ErrorCodeEnum.SUCCESS.toString());
rData.setMsg(getMsg(rData.getCode()));
rData.setData(object);
return rData;
}
public static ResponseData success(Object object, String msg) {
ResponseData rData = new ResponseData();
rData.setCode(ErrorCodeEnum.SUCCESS.toString());
rData.setMsg(getMsg(rData.getCode()));
rData.setData(msg);
return rData;
}
public static ResponseData error(ErrorCodeEnum errorCodeEnum) {
return error(errorCodeEnum, null);
}
public static ResponseData error(ErrorCodeEnum errorCodeEnum, Object object) {
ResponseData rData = new ResponseData();
rData.setCode(errorCodeEnum.toString());
rData.setMsg(getMsg(rData.getCode()));
rData.setData(object);
return rData;
}
protected static String getMsg(String code) {
Locale locale = LocaleContextHolder.getLocale();
try {
return messageSource.getMessage(code, null, locale);
} catch (NoSuchMessageException ex) {
return "";
}
}
}

View File

@@ -0,0 +1,34 @@
package com.wx.application.base;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @author zj
* @description : 实体基类 ---------------------------------
* @since 2017-10-27
*/
@Data
public class BaseEntity<FIDTYPE> {
@TableId(value = "id", type = IdType.AUTO)
private FIDTYPE id;// 物理主键
@TableField(exist = false)
@JsonIgnore
private List<FIDTYPE> ids;
@JsonIgnore
@TableField(value = "is_remove", fill = FieldFill.INSERT)
@TableLogic
private Boolean remove;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
}

View File

@@ -0,0 +1,13 @@
package com.wx.application.base;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class BaseQueryApply {
String applySql;
List<Object> value=new ArrayList<>();
}

View File

@@ -0,0 +1,15 @@
package com.wx.application.base;
import lombok.Data;
@Data
public class BaseQueryApplyOrderBy {
String sql;
Sort sort;
public enum Sort {
ASC,
DESC,
}
}

View File

@@ -0,0 +1,196 @@
package com.wx.application.base;
import cn.hutool.core.map.MapUtil;
import com.wx.application.constant.CONSTANT;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import static com.baomidou.mybatisplus.extension.toolkit.SqlHelper.retBool;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseSearchService<T extends BaseEntity<?>, M extends BaseMapper<T>> {
@Autowired
protected M simpleMapper;
protected DynamicSpecifications<T> dynamicSpecifications = new DynamicSpecifications();
/**
* 根据id查询一条
* @param id
* @return
*/
public T queryOne(Serializable id){
return (T) simpleMapper.selectById(id);
}
/**
* 读取一个对象
*
* @return
*/
@Transactional(readOnly = true)
public T queryUnique(Map map) {
AbstractWrapper wrapper = dynamicSpecifications.parseSearchParams(map);
wrapper = (AbstractWrapper) wrapper.last("limit 1");
return (T) simpleMapper.selectOne(wrapper);
}
/**
* 读取一个对象
*
* @return
*/
@Transactional(readOnly = true)
public T queryUnique(Map map,Map other) {
AbstractWrapper wrapper = dynamicSpecifications.parseSearchParams(map);
wrapper = (AbstractWrapper) wrapper.last("limit 1");
// 循环map
for(Object key : other.keySet()){
Object value = other.get(key);
wrapper.eq(key,value);
}
return (T) simpleMapper.selectOne(wrapper);
}
/**
* 查询根据ID 批量查询)
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryBatchIds(List ids) {
if(ids==null || ids.isEmpty()){
return null;
}
return simpleMapper.selectBatchIds(ids);
}
/**
* 分页查询
*
* @return
*/
@Transactional(readOnly = true)
public IPage<T> queryPage(Map map) {
Long pageNum = MapUtil.getLong(map, CONSTANT.pageNumStr);
Long pageSize = MapUtil.getLong(map, CONSTANT.pageSizeStr);
if (null == pageNum) {
pageNum = CONSTANT.pageNum;
}
if (null == pageSize) {
pageSize = CONSTANT.pageSize;
}
return simpleMapper.selectPage(new Page(pageNum, pageSize), dynamicSpecifications.parseSearchParams(map));
}
/**
* 分页查询
*
* @return
*/
@Transactional(readOnly = true)
public IPage<T> queryPage(Map map,Map other) {
Long pageNum = MapUtil.getLong(map, CONSTANT.pageNumStr);
Long pageSize = MapUtil.getLong(map, CONSTANT.pageSizeStr);
if (null == pageNum) {
pageNum = CONSTANT.pageNum;
}
if (null == pageSize) {
pageSize = CONSTANT.pageSize;
}
AbstractWrapper wrapper = dynamicSpecifications.parseSearchParams(map);
// 循环map
for(Object key : other.keySet()){
Object value = other.get(key);
wrapper.eq(key,value);
}
return simpleMapper.selectPage(new Page(pageNum, pageSize), wrapper);
}
/**
* 查询全部
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryList(Map map) {
return simpleMapper.selectList(dynamicSpecifications.parseSearchParams(map));
}
/**
* 查询全部
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryList(Map map,Map other) {
AbstractWrapper wrapper = dynamicSpecifications.parseSearchParams(map);
// 循环map
for(Object key : other.keySet()){
Object value = other.get(key);
wrapper.eq(key,value);
}
return simpleMapper.selectList(wrapper);
}
/**
* 删除数据
* @param id
* @return
*/
@Transactional
public synchronized boolean remove(Serializable id) {
return retBool(simpleMapper.deleteById(id));
}
/**
* 根据column-map删除
* @param map
* @return
*/
@Transactional
public synchronized boolean remove(Map map){
AbstractWrapper wrapper = new QueryWrapper();
// 循环map
for(Object key : map.keySet()){
Object value = map.get(key);
wrapper.eq(key,value);
}
return retBool(simpleMapper.delete(wrapper));
}
/**
* 修改数据
* @param t
* @return
*/
@Transactional
public synchronized boolean modify(T t) {
if (null == t.getId()) {
throw new RuntimeException("参数异常");
}
return retBool(simpleMapper.updateById(t));
}
/**
* 添加数据
* @param t
* @return
*/
@Transactional
public synchronized boolean create(T t) {
if (null != t.getId()) {
throw new RuntimeException("参数异常");
}
return retBool(simpleMapper.insert(t));
}
}

View File

@@ -0,0 +1,283 @@
package com.wx.application.base;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.wx.application.constant.CONSTANT;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import static com.baomidou.mybatisplus.extension.toolkit.SqlHelper.retBool;
/*import org.springframework.beans.BeanUtils;*/
/**
* @author zj
* @description : service 基类
* ---------------------------------
* @since 2017-10-27
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseService<T extends BaseEntity<?>, M extends BaseMapper<T>> {
@Autowired
protected M simpleMapper;
protected DynamicSpecifications<T> dynamicSpecifications = new DynamicSpecifications();
/**
* 读取一个对象
*
* @return
*/
@Transactional(readOnly = true)
public T queryUnique(Map map) {
AbstractWrapper wrapper = dynamicSpecifications.bySearchFilter(SearchFilter.parse(map).values());
wrapper = (AbstractWrapper) wrapper.last("limit 1");
return (T) simpleMapper.selectOne(wrapper);
}
/**
* 查询根据ID 批量查询)
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryBatchIds(List ids) {
return simpleMapper.selectBatchIds(ids);
}
@Transactional(readOnly = true)
public T getOne(Serializable id) {
return simpleMapper.selectById(id);
}
/**
* 分页查询
*
* @return
*/
public IPage<T> queryPageSort(Map map, List<BaseQueryApplyOrderBy> sorts) {
return queryPageAppender(map, null, sorts);
}
public IPage<T> queryPage(Map map) {
return queryPageAppender(map, null, null);
}
/**
* 支持累加的分页查询
*
* @param map
* @param queryApplyList
* @return
*/
@Transactional(readOnly = true)
public IPage<T> queryPageAppender(Map map, List<BaseQueryApply> queryApplyList, List<BaseQueryApplyOrderBy> orderBys) {
Long pageNum = MapUtil.getLong(map, CONSTANT.pageNumStr);
Long pageSize = MapUtil.getLong(map, CONSTANT.pageSizeStr);
if (null == pageNum) {
pageNum = CONSTANT.pageNum;
}
if (null == pageSize) {
pageSize = CONSTANT.pageSize;
}
QueryWrapper<T> queryWrapper = dynamicSpecifications.bySearchFilter(SearchFilter.parse(map).values());
if (CollectionUtil.isNotEmpty(queryApplyList)) {
queryApplyList.forEach(apply -> queryWrapper.apply(apply.getApplySql(), apply.getValue().toArray()));
}
if (CollectionUtil.isNotEmpty(orderBys)) {
orderBys.forEach(o -> {
switch (o.getSort()) {
case ASC:
queryWrapper.orderByAsc(o.getSql());
case DESC:
queryWrapper.orderByDesc(o.getSql());
default:
}
});
}
return simpleMapper.selectPage(new Page(pageNum, pageSize), queryWrapper);
}
public Page toPage(Map map) {
Long pageNum = MapUtil.getLong(map, CONSTANT.pageNumStr);
Long pageSize = MapUtil.getLong(map, CONSTANT.pageSizeStr);
if (null == pageNum) {
pageNum = CONSTANT.pageNum;
}
if (null == pageSize) {
pageSize = CONSTANT.pageSize;
}
return new Page(pageNum, pageSize);
}
/**
* 查询全部
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryList(Map map) {
return simpleMapper.selectList(dynamicSpecifications.bySearchFilter(SearchFilter.parse(map).values()));
}
/**
* 查询全部
*
* @return
*/
@Transactional(readOnly = true)
public List<T> queryListAppender(Map map, List<BaseQueryApply> queryApplyList) {
QueryWrapper<T> queryWrapper = dynamicSpecifications.bySearchFilter(SearchFilter.parse(map).values());
if (CollectionUtil.isNotEmpty(queryApplyList)) {
queryApplyList.forEach(apply -> queryWrapper.apply(apply.getApplySql(), apply.getValue().toArray()));
}
return simpleMapper.selectList(queryWrapper);
}
@Transactional
public synchronized boolean remove(Serializable id) {
return retBool(simpleMapper.deleteById(id));
}
@Transactional
public synchronized boolean modify(T t) {
if (null == t.getId()) {
throw new RuntimeException("参数异常");
}
return retBool(simpleMapper.updateById(t));
}
@Transactional
public synchronized T create(T t) {
if (null != t.getId()) {
throw new RuntimeException("参数异常");
}
simpleMapper.insert(t);
return t;
}
@Transactional
public synchronized boolean createOrUpdate(T t) {
if (null == t.getId()) {
return retBool(simpleMapper.insert(t));
}
return retBool(simpleMapper.updateById(t));
}
@Transactional
public synchronized boolean removeBatch(List<Long> ids) {
return retBool(simpleMapper.deleteBatchIds(ids));
}
/**
* 批量插入
*
* @throws DbException
*/
@Transactional
public boolean insertBatch(List<T> entityList) {
int batchSize = 20;
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatementByXml(SqlMethod.INSERT_ONE.getMethod());
for (int i = 0; i < size; i++) {
batchSqlSession.insert(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
e.printStackTrace();
}
return true;
}
/**
* 批量更新
*/
@Transactional
public boolean updateBatch(List<T> entityList) {
int batchSize = 20;
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatementByXml("updateBatch");
for (int i = 0; i < size; i++) {
batchSqlSession.update(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
e.printStackTrace();
}
return true;
}
/**
* 自定义批量插入
* @param entityList
* @param batchSize
* @return
* @throws Exception
*/
@Transactional
public boolean insertBatchByXml(List<T> entityList) {
int batchSize = 20;
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatementByXml("insertBatch");
for (int i = 0; i < size; i++) {
batchSqlSession.insert(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
e.printStackTrace();
}
return true;
}
protected Class currentModelClass() {
return ReflectionKit.getSuperClassGenericType(getClass(), 0);
}
/**
* 批量操作 SqlSession
*/
protected SqlSession sqlSessionBatch() {
return SqlHelper.sqlSessionBatch(currentModelClass());
}
/**
* 获取SqlStatement
*/
protected String sqlStatementByXml(String method) {
return SqlHelper.table(currentModelClass()).getSqlStatement(method);
}
}

View File

@@ -0,0 +1,309 @@
package com.wx.application.base;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import java.util.Collection;
import java.util.Map;
@SuppressWarnings({"rawtypes", "hiding"})
public class DynamicSpecifications<T extends BaseEntity<?>> {
/**
* 开始构造表达式
*
* @param filters
* @param <T>
* @return
*/
@SuppressWarnings({"incomplete-switch"})
public <T> QueryWrapper<T> bySearchFilter(final Collection<SearchFilter> filters) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
if (CollectionUtil.isNotEmpty(filters)) {
for (SearchFilter filter : filters) {
filter.fieldName = StrUtil.toUnderlineCase(filter.fieldName);
// nested path translate, 如Task的名为"user.name"的filedName, 转换为Task.user.name属性
// fixme 暂不支持级联查询
if (filter.logic != null) {
switch (filter.logic) {
case OR:
queryWrapper = queryWrapper.or();
break;
}
}
if (filter.operator == null) {
continue;
}
switch (filter.operator) {
case EQ:
queryWrapper = queryWrapper.eq(filter.fieldName, filter.value);
break;
case LIKE:
queryWrapper = queryWrapper.like(filter.fieldName, filter.value);
break;
case GT:
queryWrapper = queryWrapper.gt(filter.fieldName, filter.value);
break;
case LT:
queryWrapper = queryWrapper.lt(filter.fieldName, filter.value);
break;
case GTE:
queryWrapper = queryWrapper.ge(filter.fieldName, filter.value);
break;
case LTE:
queryWrapper = queryWrapper.le(filter.fieldName, filter.value);
break;
case IN:
queryWrapper = queryWrapper.in(filter.fieldName, StrUtil.split(filter.value.toString(), ',', -1));
break;
case NIN:
queryWrapper = queryWrapper.notIn(filter.fieldName, StrUtil.split(filter.value.toString(), ',', -1));
break;
case NEQ:
queryWrapper = queryWrapper.ne(filter.fieldName, filter.value);
break;
case FIELDEQ:
queryWrapper = queryWrapper.apply(StrUtil.format("{}={}", filter.fieldName, filter.value));
break;
case ISNOTNULL:
queryWrapper = queryWrapper.isNotNull(filter.fieldName);
break;
case ISNULL:
queryWrapper = queryWrapper.isNull(filter.fieldName);
break;
case ISEMPTY:
queryWrapper = queryWrapper.eq(filter.fieldName, "");
break;
case ISNOTEMPTY:
queryWrapper = queryWrapper.ne(filter.fieldName, "");
break;
case FIELDNEQ:
queryWrapper = queryWrapper.apply(StrUtil.format("{}!={}", filter.fieldName, filter.value));
break;
case DESC:
queryWrapper.orderByDesc(filter.fieldName);
break;
case DESCA:
queryWrapper.orderByDesc(filter.value.toString().split(","));
break;
case ASC:
queryWrapper.orderByAsc(filter.fieldName);
break;
case ASCA:
queryWrapper.orderByAsc(filter.value.toString().split(","));
break;
}
}
}
return queryWrapper;
}
/**
* 直接解析map的方式
*
* @param map
* @param <T>
* @return
*/
public <T> QueryWrapper<T> parseSearchParams(Map map) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
// 获取排序字段,支持多个
String order = MapUtil.getStr(map, "order");
// 获取排序类型
String by = StrUtil.isBlank(MapUtil.getStr(map, "by")) ? "asc" : MapUtil.getStr(map, "by");
// 设置查询条件
String searchParam = MapUtil.getStr(map, "searchParam");
queryWrapper = parseSearchParams(searchParam);
// 如果需要排序
if (!StrUtil.isBlank(order)) {
// 多个字段一起排序
if (order.contains("|")) {
// 多个字段排序
String[] orders = StringUtils.split(order, "|");
for (int i = 0; i < orders.length; i++) {
// 设置order
if (by.toLowerCase().equals("desc")) {
queryWrapper.orderByDesc(StrUtil.toUnderlineCase(orders[i]));
} else {
queryWrapper.orderByAsc(StrUtil.toUnderlineCase(orders[i]));
}
}
}
// 单个字段排序
else {
// 设置order
if (by.toLowerCase().equals("desc")) {
queryWrapper.orderByDesc(StrUtil.toUnderlineCase(order));
} else {
queryWrapper.orderByAsc(StrUtil.toUnderlineCase(order));
}
}
}
return queryWrapper;
}
/**
* 解析json字符串为查询参数
*
* @param searchParam
* @param <T>
* @return
*/
public <T> QueryWrapper<T> parseSearchParams(String searchParam) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
try {
JSONArray searchData = JSONArray.parseArray(searchParam);
queryWrapper = parseSearchParams(searchData, null);
} catch (Exception e) {
}
return queryWrapper;
}
/**
* 解析jsonarray为查询参数
*
* @param searchParam
* @param <T>
* @return
*/
public <T> QueryWrapper<T> parseSearchParams(JSONArray searchParam, QueryWrapper<T> queryWrapper) {
// 定义返回参数
if (queryWrapper == null) {
queryWrapper = new QueryWrapper<>();
}
for (int i = 0; i < searchParam.size(); i++) {
JSONObject item = searchParam.getJSONObject(i);
// 如果是组模式
if (SearchFilter.Mod.group.toString().equals(item.getString("mod"))) {
// 如果是or连接
if (SearchFilter.Logic.OR.toString().toLowerCase().equals(item.getString("logic").toLowerCase())) {
// 如果存在子节点
if (item.getJSONArray("children") != null) {
queryWrapper.or((wrapper) -> {
parseSearchParams(item.getJSONArray("children"), wrapper);
});
}
}
// 如果是and连接
else {
// 如果存在子节点
if (item.getJSONArray("children") != null) {
queryWrapper.and((wrapper) -> {
parseSearchParams(item.getJSONArray("children"), wrapper);
});
}
}
}
// 如果是条件模式
else {
// 表达式
String operator = item.getString("operator");
// 查询字段,支持复合字段
String fieldName = item.getString("field");
// 后续转化根据类型
String type = item.getString("type");
// 查询值
Object value = item.getString("value");
// 连接符
String logic = StrUtil.isBlank(item.getString("logic")) ? "and" : item.getString("logic");
// 如果是多字段查询同一个值
if (fieldName.contains("|")) {
String[] fields = StringUtils.split(fieldName, "|");
// 如果是and连接符
if (logic.toLowerCase().equals("and")) {
queryWrapper.and((wrapper) -> {
for (int j = 0; j < fields.length; j++) {
wrapper.or();
consumption(wrapper, operator, fields[j], value);
}
});
}
// 如果是or连接符
else {
queryWrapper.or((wrapper) -> {
for (int j = 0; j < fields.length; j++) {
wrapper.or();
consumption(wrapper, operator, fields[j], value);
}
});
}
} else {
// 如果是or连接符
if (!StrUtil.isBlank(logic) && logic.toLowerCase().equals("and")) {
queryWrapper.or();
}
consumption(queryWrapper, operator, fieldName, value);
}
}
}
return queryWrapper;
}
public <T> QueryWrapper<T> consumption(QueryWrapper<T> queryWrapper, String operator, String fieldName, Object value) {
// 转换字段名格式,把 驼峰转为数据库下划线形式
fieldName = StrUtil.toUnderlineCase(fieldName);
if (!StrUtil.isBlank(operator)) {
switch (operator.toUpperCase()) {
case "EQ":
queryWrapper = queryWrapper.eq(fieldName, value);
break;
case "LIKE":
queryWrapper = queryWrapper.like(fieldName, value);
break;
case "GT":
queryWrapper = queryWrapper.gt(fieldName, value);
break;
case "LT":
queryWrapper = queryWrapper.lt(fieldName, value);
break;
case "GTE":
queryWrapper = queryWrapper.ge(fieldName, value);
break;
case "LTE":
queryWrapper = queryWrapper.le(fieldName, value);
break;
case "IN":
queryWrapper = queryWrapper.in(fieldName, StrUtil.split(value.toString(), ',',-1));
break;
case "NEQ":
queryWrapper = queryWrapper.ne(fieldName, value);
break;
case "FIELDEQ":
queryWrapper = queryWrapper.apply(StrUtil.format("{}={}", fieldName, value));
break;
case "ISNOTNULL":
queryWrapper = queryWrapper.isNotNull(fieldName);
break;
case "ISNULL":
queryWrapper = queryWrapper.isNull(fieldName);
break;
case "ISEMPTY":
queryWrapper = queryWrapper.eq(fieldName, "");
break;
case "ISNOTEMPTY":
queryWrapper = queryWrapper.ne(fieldName, "");
break;
case "FIELDNEQ":
queryWrapper = queryWrapper.apply(StrUtil.format("{}!={}", fieldName, value));
break;
case "DESC":
queryWrapper.orderByDesc(fieldName);
break;
case "ASC":
queryWrapper.orderByAsc(fieldName);
break;
}
}
return queryWrapper;
}
}

View File

@@ -0,0 +1,50 @@
package com.wx.application.base;
/**
* 错误码枚举
*/
public enum ErrorCodeEnum {
SUCCESS,
SYSTEM_ERROR,
PARAM_ERROR,
UNAUTHORIZED,
AUTHORIZATION_EXPIRED,
LOGIN_ERROR,
// 旧密码错误
OLD_PASSWORD_ERROR,
NO_PERMISSION,
NO_PROFESSOR_EXIST,
MOBILE_USED,
USER_NOT_EXIST,
ROTATEMENT_NOT_EXIST,
ROTATEMENT_HAS_BEEN_MARKED,
// 已签到
SIGNED_IN,
// 混合购物
MIXED_SHOPPING,
// 商品不存在
GOOD_ITEM_NOT_FOUND,
GOOD_ITEM_NOT_ENOUGH,
// 订单商品为空
ORDER_ITEM_IS_EMPTY,
// 租赁日期不合法
LEASE_DAY_INCORRECT,
// 服务器内部错误
INTERNAL_ERROR,
// 已经签约过
ALREADY_SIGNED,
UNIT_NAME_EXIST,
MEDICAL_INSURANCE_NAME_EXIST,
NURSE_NAME_EXIST,
DOCTOR_NAME_EXIST,
DEPARTMENT_NAME_EXIST,
MSG_TO_FAST,
SECURITY_CODE_INVALID
}

View File

@@ -0,0 +1,58 @@
package com.wx.application.base;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* @author zj
* @description : restful 接口返回封装
* ---------------------------------
* @since 2017-10-27
*/
@Data
@Accessors(chain = true)
public class ResponseData<T> {
//请求id
private String code;
// 状态码
private String msg;
//状态信息
private T data;
// 具体内容
private String requestId;
public static ResponseData SUCCESS(String msg, Object data) {
ResponseData responseData = new ResponseData();
responseData.msg = msg;
responseData.data = data;
responseData.code = ErrorCodeEnum.SUCCESS.toString();
return responseData;
}
public static ResponseData ERROR(String msg, Object data) {
ResponseData responseData = new ResponseData();
responseData.msg = msg;
responseData.data = data;
responseData.code = ErrorCodeEnum.SYSTEM_ERROR.toString();
return responseData;
}
public static ResponseData ERROR(ErrorCodeEnum codeEnum, String msg, Object data) {
ResponseData responseData = new ResponseData();
responseData.msg = msg;
responseData.data = data;
responseData.code = codeEnum.toString();
return responseData;
}
public static ResponseData ERROR(String codeValue, String msg, Object data) {
ResponseData responseData = new ResponseData();
responseData.msg = msg;
responseData.data = data;
responseData.code = codeValue;
return responseData;
}
}

View File

@@ -0,0 +1,176 @@
package com.wx.application.base;
import cn.hutool.core.convert.Convert;
import com.google.common.collect.Maps;
import com.wx.application.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
/**
* sql查询构建器
*/
public class SearchFilter {
public enum Operator {
EQ,//值相等
NEQ, //值不等
LIKE, //值模糊匹配
GT, //大于
LT, //小于
GTE, //大于等于
LTE,//小于等于
IN,//在某个范围内
NIN,//不在某个范围内
FIELDEQ,//一个字段等于另一个字段
FIELDNEQ,//一个字段不等于另一个字段
ISNULL,
ISNOTNULL,
ISEMPTY,
ISNOTEMPTY,
DESC, // 降序
DESCA,//多个字段降序
ASC, // 升序
ASCA,//多个字段升序
}
public enum Logic {
AND, OR
}
/**
* 模式
*/
public enum Mod {
// 条件
condition,
// 分组
group
}
/**
* 属性数据类型.
*/
public enum PropertyType {
S(String.class), // 字符串
I(Integer.class), // 数字
L(Long.class), // 长整型一般用作ID查询
N(Double.class), // 双精度
D(Date.class), // 日期
B(Boolean.class), // 布尔类型
C(BigDecimal.class);
private Class<?> clazz;
private PropertyType(Class<?> clazz) {
this.clazz = clazz;
}
public Class<?> getValue() {
return clazz;
}
}
//字段名称
public String fieldName;
//值
public Object value;
//eq ue
public Operator operator;
//and or
public Logic logic;
public SearchFilter(String fieldName, Operator operator, Object value) {
this.fieldName = fieldName;
this.value = value;
this.operator = operator;
}
public SearchFilter(String fieldName, Operator operator, Object value, Logic logic) {
this.fieldName = fieldName;
this.value = value;
this.operator = operator;
this.logic = logic;
}
/**
* 解析下map中的值,挑选符合条件的备用
* searchParams中key的格式为OPERATOR_FIELDNAME
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
Map<String, SearchFilter> filters = Maps.newHashMap();
for (Entry<String, Object> entry : searchParams.entrySet()) {
// 过滤掉空值
String key = entry.getKey();
Object value = entry.getValue();
if (StringUtils.isBlank(value.toString())) {
continue;
}
// 拆分operator与filedAttribute
String[] names = StringUtils.split(key, "_");
if (names.length == 2) {
String filedName = names[1];
String firstPart = names[0];
String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());
Operator operator = Operator.valueOf(matchTypeCode);
Class propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
Object obj = null;
if(operator.equals(Operator.LTE) && propertyTypeCode.equals("D")) {
String v = DateUtils.fn1(1, value.toString());
obj = Convert.convert(propertyClass, v);
} else {
obj = Convert.convert(propertyClass, value);
}
// 创建searchFilter
SearchFilter filter = new SearchFilter(filedName, operator, obj);
filters.put(key, filter);
} else if (names.length == 3) {
String filedName = names[1];
String firstPart = names[0];
String logicName = names[2];
String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());
Operator operator = Operator.valueOf(matchTypeCode);
Logic logic = Logic.valueOf(logicName);
//List<Object> objects = new ArrayList<Object>();
Class propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
Object obj = Convert.convert(propertyClass, value);
;
//String valueString = String.valueOf(value);
//fixme暂不支持级联
/*if (valueString.contains("#")) {
String[] values = StringUtils.split(valueString, "#");
for (String val : values) {
Class propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
obj = Convert.convert(propertyClass, value);
objects.add(obj);
}
} else {
String[] values = StringUtils.split(valueString, "_");
for (String val : values) {
Class propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
obj = Convert.convert(propertyClass, value);
objects.add(obj);
}
}*/
// 创建searchFilter
SearchFilter filter = new SearchFilter(filedName, operator, obj, logic);
filters.put(key, filter);
}
}
return filters;
}
}

View File

@@ -0,0 +1,41 @@
package com.wx.application.configuration;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.ArrayList;
import java.util.List;
/**
* 放行参数配置
*/
@Data
@Configuration
@ConditionalOnExpression("!'${ignore}'.isEmpty()")
@ConfigurationProperties(prefix = "ignore")
public class FilterIgnorePropertiesConfig {
/**
* 放行终端配置,网关不校验此处的终端
*/
private List<String> clients = new ArrayList<>();
/**
* 放行url,放行的url不再被安全框架拦截
*/
private List<String> urls = new ArrayList<>();
/**
* 不聚合swagger
*/
private List<String> swaggerProviders = new ArrayList<>();
@Bean
public Validator validator() {
return new LocalValidatorFactoryBean();
}
}

View File

@@ -0,0 +1,29 @@
package com.wx.application.configuration;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 自动填充创建项
*/
@Slf4j
@Component
public class MybatisFillHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
this.setFieldValByName("remove", false, metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}

View File

@@ -0,0 +1,7 @@
package com.wx.application.configuration.annotation;
/**
* 关闭切面注解
*/
public @interface AspectOff {
}

View File

@@ -0,0 +1,18 @@
package com.wx.application.configuration.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AuditLog {
String title() default "";
/**
* 操作资源类型
*/
String opType() default "";
}

View File

@@ -0,0 +1,52 @@
package com.wx.application.constant;
/**
* 系统运行时一些常量
*/
public interface CONSTANT {
//分页大小名称
String pageSizeStr = "pageSize";
//默认分页大小
Long pageSize = 10L;
//当前页名称
String pageNumStr = "pageNo";
//默认分页名称
Long pageNum = 1L;
String REQUEST_ID_KEY = "REQ_ID";
String REQUEST_URL = "REQ_URL";
String X_REQ_ID = "X-Request-Id";
String OP_RESOURCE_NAME = "OP_RESOURCE_NAME";
/**
* 请求号header标识
*/
String TOKEN_NAME = "Authorization";
String MD5_ID = "Md5id";
String USER_SIGN = "usrSign";
String USER_SIGN_NAME = "usrSignName";
String JWT_USER_TAG = "JWT_USER_TAG";
String LOGIN_TYPE_ADMIN = "LOGIN_TYPE_ADMIN";
String COSURL = "https://yzhishuimian-1301717583.cos.ap-beijing.myqcloud.com/";
String[] imgArr = {"bmp", "jpg", "png", "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
"cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp"};
String[] videoArr = {"avi", "mpeg", "mpg", "dat", "ra", "rm", "rmvb", "mov", "qt", "flv", "wmv",
"asf", "mkv", "mp4", "m4v"};
//用户ip
String IP = "IP";
//订单默认超时时间分钟
public final static int ORDER_EXPIRE = 60;
Integer batch_create_max = 2000;
Integer maxAggregation = 10000000;
Integer nebula_batch_create_max = 500;
}

View File

@@ -0,0 +1,53 @@
package com.wx.application.core.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.entity.GraphCase;
import com.wx.application.core.service.GraphCaseService;
/**
* @description : GraphCase 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-09-23
*/
/*@Slf4j*/
@RestController("coreGraphCaseController")
@RequestMapping("/graph-case")
public class GraphCaseController extends BaseController {
@Autowired
private GraphCaseService graphCaseService;
@PostMapping(value = "/create")
public ResponseData create(@RequestBody GraphCase graphCase) {
return success(graphCaseService.createGraphCase(graphCase));
}
@PostMapping(value = "/query_pages")
public ResponseData queryPages(@RequestBody Map ontologyQ) {
return success(graphCaseService.queryPage(ontologyQ));
}
@PostMapping(value = "/remove/{id}")
public ResponseData remove(@PathVariable("id") Long id) {
graphCaseService.removeGraphCase(id);
return success();
}
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody GraphCase graphCase) {
return success(graphCaseService.modify(graphCase));
}
}

View File

@@ -0,0 +1,41 @@
package com.wx.application.core.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.service.GraphTaskService;
/**
* @description : GraphTask 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-08-02
*/
/*@Slf4j*/
@RestController("coreGraphTaskController")
@RequestMapping("/graph-task")
public class GraphTaskController extends BaseController {
@Autowired
private GraphTaskService graphTaskService;
/**
* 根据实例空间名查看现在是不是有任务在导入
* @param space
* @return
*/
@GetMapping(value = "/query_list/{space}")
public ResponseData queryList(@PathVariable("space") String space) {
Map mQ = new HashMap<>();
mQ.put("EQI_status", 0);
mQ.put("EQS_space", space);
return success(graphTaskService.queryList(mQ));
}
}

View File

@@ -0,0 +1,117 @@
package com.wx.application.core.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.adapter.dto.qo.OntologyQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.entity.OntologyConcept;
import com.wx.application.core.service.OntologyConceptService;
/**
* @description : OntologyConcept 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-09-25
*/
/*@Slf4j*/
@RestController("coreOntologyConceptController")
@RequestMapping("/ontology-concept")
public class OntologyConceptController extends BaseController {
@Autowired
private OntologyConceptService ontologyConceptService;
/**
* 查询树形
* @param ontologyId
* @param ontologyConceptQ
* @return
*/
@PostMapping(value = "/query_list/{ontologyId}")
public ResponseData queryList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody Map ontologyConceptQ) {
ontologyConceptQ.put("EQL_ontologyId", ontologyId);
return success(ontologyConceptService.queryList(ontologyConceptQ));
}
/**
* 模糊匹配
*/
@PostMapping(value = "/like_list/{ontologyId}")
public ResponseData likeList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody OntologyQ ontologyQ) {
if(StringUtils.isBlank(ontologyQ.getLabel())) {
return success();
}
Map mQ = new HashMap<>();
mQ.put("EQL_ontologyId", ontologyId);
mQ.put("LIKES_label", ontologyQ.getLabel());
return success(ontologyConceptService.queryList(mQ));
}
/**
* 概念数量 对象属性数量 值属性数量
* @param ontologyId
* @return
*/
@GetMapping(value = "/countallbyontologyid/{ontologyId}")
public ResponseData countAllByOntologyId(@PathVariable("ontologyId") Long ontologyId) {
return success(ontologyConceptService.countAllByOntologyId(ontologyId));
}
/**
* 统计次级概念数量
*/
@GetMapping(value = "/countchildbyid/{id}")
public ResponseData countChildbyid(@PathVariable("id") Long id) {
return success(ontologyConceptService.countChildbyid(id));
}
/**
* 删除树形节点
* @param ownId
* @return
*/
@GetMapping(value = "/delete/{id}")
public ResponseData delete(@PathVariable("id") Long id) {
return success(ontologyConceptService.deleteOntologyConcept(id));
}
/**
* 修改
* @param ontologyConcept
* @return
*
* 传修改 改成 传 {ownIdlabel}
*/
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody OntologyConcept ontologyConcept) {
return success(ontologyConceptService.modifyOntologyConcept(ontologyConcept));
}
/**
* 创建
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/create")
public ResponseData create(@RequestBody OntologyConcept ontologyConcept) {
return success(ontologyConceptService.createOntologyConcept(ontologyConcept));
}
}

View File

@@ -0,0 +1,274 @@
package com.wx.application.core.controller;
import org.springframework.web.bind.annotation.*;
import com.wx.application.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import com.wx.application.core.service.OntologyService;
import com.wx.application.core.entity.Ontology;
import com.wx.application.base.ResponseData;
import java.util.Map;
import java.io.Serializable;
/**
* @description : Ontology 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-03-14
*/
/*@Slf4j*/
@RestController("coreOntologyController")
@RequestMapping("/ontology")
public class OntologyController extends BaseController {
@Autowired
private OntologyService ontologyService;
@PostMapping(value = "/getone/{id}")
public ResponseData getOne(@PathVariable("id") Serializable id) {
return success(ontologyService.getOne(id));
}
/**
* 定义一些通用的错误信息,供其他 api引用
* @apiDefine DefaultException
* @apiError {String} code 错误码
* @apiError {String} msg 错误描述
* @apiError {String} requestId 请求id标识
*
* @apiErrorExample Error-Response:
* HTTP/1.1 200
* {
* "code": "UNAUTHORIZED",
* "msg": "未授权,请先登录",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
*/
/**
* 定义标准对象请求的结构体,供api引用
* @apiDefine OntologyReq
* @apiParam {String} name
* @apiParam {String} describe
*/
/**
* 定义标准对象返回的结构体,供api引用
* @apiDefine OntologyResp
* @apiSuccess {String} name
* @apiSuccess {String} describe
*/
/**
* 定义标准头部,供api引用
* @apiDefine OntologyHeader
* @apiHeader {String} Authorization 用户授权token
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 1eyJhbGciOiJIUzI1NiJ9....tzNK43MPVQWYYhDwihCAZa88zXzar7KLdgiBBDuUpBM",
* }
*/
/**
*
* @api {post} //ontology/query_unique 通过条件查询对象
* @apiName 通过条件查询对象
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiUse OntologyResp
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": {
"name": null,
"describe": null,
* },
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件查询对象
* 仅查询第一条
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/query_unique")
public ResponseData queryUnique(@RequestBody Map ontologyQ) {
return success(ontologyService.queryUnique(ontologyQ));
}
/**
*
* @api {post} //ontology/query_pages 通过条件分页查询列表
* @apiName 通过条件分页查询列表
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiUse OntologyResp
* @apiSuccess {Long} total 总数
* @apiSuccess {Long} size 分页大小
* @apiSuccess {Long} current 当前页
* @apiSuccess {Long} orders 排序
* @apiSuccess {Long} pages 总页数
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": {
* "records": [{
"name": null,
"describe": null, * }],
* "total": 1,
* "size": 10,
* "current": 1,
* "orders": [],
* "searchCount": true,
* "pages": 1
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件分页查询列表
* 默认第一页 分页长度为10
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/query_pages")
public ResponseData queryPages(@RequestBody Map ontologyQ) {
return success(ontologyService.queryPage(ontologyQ));
}
/**
*
* @api {post} //ontology/query_list 通过条件查询列表
* @apiName 通过条件查询列表
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiUse OntologyResp
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": [{
"name": null,
"describe": null,
* }],
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件查询列表
* 不分页直接返回list
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/query_list")
public ResponseData queryList(@RequestBody Map ontologyQ) {
return success(ontologyService.queryList(ontologyQ));
}
/**
*
* @api {post} //ontology/remove/:id 通过id删除单个记录
* @apiName 通过id删除单个记录
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiParam {PK} id 记录主键
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过id删除单个记录
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/remove/{id}")
public ResponseData remove(@PathVariable("id") Serializable id) {
return success(ontologyService.remove(id));
}
/**
*
* @api {post} //ontology/modify 通过id更新单个记录
* @apiName 通过id更新单个记录
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiParam {PK} id 记录主键
* @apiUse OntologyReq
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过id更新单个记录
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody Ontology ontology) {
return success(ontologyService.modify(ontology));
}
/**
*
* @api {post} //ontology/create 新增
* @apiName 新增
* @apiGroup Ontology
*
* @apiUse OntologyHeader
* @apiUse OntologyReq
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 新增
* ---------------------------------
* @author : zj
* @since : Create in 2022-03-14
*/
@PostMapping(value = "/create")
public ResponseData create(@RequestBody Ontology ontology) {
return success(ontologyService.create(ontology));
}
}

View File

@@ -0,0 +1,112 @@
package com.wx.application.core.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.adapter.dto.qo.OntologyQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.entity.OntologyField;
import com.wx.application.core.service.OntologyFieldService;
import com.wx.application.nebula.graph.base.Generators;
/**
* @description : OntologyField 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-09-25
*/
/*@Slf4j*/
@RestController("coreOntologyFieldController")
@RequestMapping("/ontology-field")
public class OntologyFieldController extends BaseController {
@Autowired
private OntologyFieldService ontologyFieldService;
/**
* 查询树形
* @param ontologyId
* @param ontologyConceptQ
* @return
*/
@PostMapping(value = "/query_list/{ontologyId}")
public ResponseData queryList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody Map ontologyConceptQ) {
ontologyConceptQ.put("EQL_ontologyId", ontologyId);
return success(ontologyFieldService.queryList(ontologyConceptQ));
}
/**
* 模糊匹配
* @param ontologyId
* @param ontologyQ
* @return
*/
@PostMapping(value = "/like_list/{ontologyId}")
public ResponseData likeList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody OntologyQ ontologyQ) {
if(StringUtils.isBlank(ontologyQ.getLabel())) {
return success();
}
Map mQ = new HashMap<>();
mQ.put("EQL_ontologyId", ontologyId);
mQ.put("LIKES_comment", ontologyQ.getLabel());
return success(ontologyFieldService.queryList(mQ));
}
/**
* 删除树形节点
* @param ownId
* @return
*/
@GetMapping(value = "/delete/{id}")
public ResponseData delete(@PathVariable("id") Long id) {
ontologyFieldService.deleteConceptField(id);
return success();
}
/**
* 修改
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody OntologyField ontologyField) {
ontologyFieldService.modifyOntologyField(ontologyField);
return success();
}
/**
* 创
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/createconceptfield")
public ResponseData createConceptField(@RequestBody OntologyField ontologyField) {
ontologyFieldService.createConceptField(ontologyField);
return success();
}
/**
* 创建关系名称
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/create")
public ResponseData create(@RequestBody OntologyField ontologyField) {
if(StringUtils.isBlank(ontologyField.getField())) {
ontologyField.setField(Generators.fieldname(ontologyField.getComment()));
}
return success(ontologyFieldService.createOntologyField(ontologyField));
}
}

View File

@@ -0,0 +1,103 @@
package com.wx.application.core.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.adapter.dto.qo.OntologyQ;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.core.entity.OntologyRelation;
import com.wx.application.core.service.OntologyRelationService;
/**
* @description : OntologyRelation 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-09-25
*/
/*@Slf4j*/
@RestController("coreOntologyRelationController")
@RequestMapping("/ontology-relation")
public class OntologyRelationController extends BaseController {
@Autowired
private OntologyRelationService ontologyRelationService;
/**
* 查询树形
* @param ontologyId
* @param ontologyConceptQ
* @return
*/
@PostMapping(value = "/query_list/{ontologyId}")
public ResponseData queryList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody Map ontologyConceptQ) {
ontologyConceptQ.put("EQL_ontologyId", ontologyId);
return success(ontologyRelationService.queryList(ontologyConceptQ));
}
/**
* 模糊匹配
*/
@PostMapping(value = "/like_list/{ontologyId}")
public ResponseData likeList(@PathVariable("ontologyId") Long ontologyId,
@RequestBody OntologyQ ontologyQ) {
if(StringUtils.isBlank(ontologyQ.getLabel())) {
return success();
}
Map mQ = new HashMap<>();
mQ.put("EQL_ontologyId", ontologyId);
mQ.put("LIKES_label", ontologyQ.getLabel());
return success(ontologyRelationService.queryList(mQ));
}
/**
* 删除树形节点
* @param ownId
* @return
*/
@GetMapping(value = "/delete/{id}")
public ResponseData delete(@PathVariable("id") Long id) {
return success(ontologyRelationService.deleteOntologyRelation(id));
}
/**
* 修改
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody OntologyRelation ontologyRelation) {
return success(ontologyRelationService.modifyOntologyRelation(ontologyRelation));
}
/**
* 创建关系 选择头节点和尾节点
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/createrelations")
public ResponseData createRelations(@RequestBody OntologyRelation ontologyRelation) {
return success(ontologyRelationService.createRelations(ontologyRelation));
}
/**
* 创建关系名称
* @param ontologyConcept
* @return
*/
@PostMapping(value = "/create")
public ResponseData create(@RequestBody OntologyRelation ontologyRelation) {
return success(ontologyRelationService.createOntologyRelation(ontologyRelation));
}
}

View File

@@ -0,0 +1,268 @@
package com.wx.application.core.controller;
import org.springframework.web.bind.annotation.*;
import com.wx.application.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import com.wx.application.core.service.QuestionQaService;
import com.wx.application.core.entity.QuestionQa;
import com.wx.application.base.ResponseData;
import java.util.Map;
import java.io.Serializable;
/**
* @description : QuestionQa 默认控制器,仅供生成器使用
* ---------------------------------
* @since 2022-05-31
*/
/*@Slf4j*/
@RestController("coreQuestionQaController")
@RequestMapping("/question_qa")
public class QuestionQaController extends BaseController {
@Autowired
private QuestionQaService questionQaService;
/**
* 定义一些通用的错误信息,供其他 api引用
* @apiDefine DefaultException
* @apiError {String} code 错误码
* @apiError {String} msg 错误描述
* @apiError {String} requestId 请求id标识
*
* @apiErrorExample Error-Response:
* HTTP/1.1 200
* {
* "code": "UNAUTHORIZED",
* "msg": "未授权,请先登录",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
*/
/**
* 定义标准对象请求的结构体,供api引用
* @apiDefine QuestionQaReq
* @apiParam {String} question
* @apiParam {String} answer
*/
/**
* 定义标准对象返回的结构体,供api引用
* @apiDefine QuestionQaResp
* @apiSuccess {String} question
* @apiSuccess {String} answer
*/
/**
* 定义标准头部,供api引用
* @apiDefine QuestionQaHeader
* @apiHeader {String} Authorization 用户授权token
* @apiHeaderExample {json} Header-Example:
* {
* "Authorization": "Bearer 1eyJhbGciOiJIUzI1NiJ9....tzNK43MPVQWYYhDwihCAZa88zXzar7KLdgiBBDuUpBM",
* }
*/
/**
*
* @api {post} //question-qa/query_unique 通过条件查询对象
* @apiName 通过条件查询对象
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiUse QuestionQaResp
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": {
"question": null,
"answer": null,
* },
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件查询对象
* 仅查询第一条
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/query_unique")
public ResponseData queryUnique(@RequestBody Map questionQaQ) {
return success(questionQaService.queryUnique(questionQaQ));
}
/**
*
* @api {post} //question-qa/query_pages 通过条件分页查询列表
* @apiName 通过条件分页查询列表
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiUse QuestionQaResp
* @apiSuccess {Long} total 总数
* @apiSuccess {Long} size 分页大小
* @apiSuccess {Long} current 当前页
* @apiSuccess {Long} orders 排序
* @apiSuccess {Long} pages 总页数
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": {
* "records": [{
"question": null,
"answer": null, * }],
* "total": 1,
* "size": 10,
* "current": 1,
* "orders": [],
* "searchCount": true,
* "pages": 1
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件分页查询列表
* 默认第一页 分页长度为10
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/query_pages")
public ResponseData queryPages(@RequestBody Map questionQaQ) {
return success(questionQaService.queryPage(questionQaQ));
}
/**
*
* @api {post} //question-qa/query_list 通过条件查询列表
* @apiName 通过条件查询列表
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiUse QuestionQaResp
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": [{
"question": null,
"answer": null,
* }],
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过条件查询列表
* 不分页直接返回list
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/query_list")
public ResponseData queryList(@RequestBody Map questionQaQ) {
return success(questionQaService.queryList(questionQaQ));
}
/**
*
* @api {post} //question-qa/remove/:id 通过id删除单个记录
* @apiName 通过id删除单个记录
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiParam {PK} id 记录主键
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过id删除单个记录
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/remove/{id}")
public ResponseData remove(@PathVariable("id") Serializable id) {
return success(questionQaService.remove(id));
}
/**
*
* @api {post} //question-qa/modify 通过id更新单个记录
* @apiName 通过id更新单个记录
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiParam {PK} id 记录主键
* @apiUse QuestionQaReq
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 通过id更新单个记录
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/modify")
public ResponseData modify(@RequestBody QuestionQa questionQa) {
return success(questionQaService.modify(questionQa));
}
/**
*
* @api {post} //question-qa/create 新增
* @apiName 新增
* @apiGroup QuestionQa
*
* @apiUse QuestionQaHeader
* @apiUse QuestionQaReq
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* {
* "data": true,
* "code": "SUCCESS",
* "msg": "请求成功",
* "requestId": "163e2f67-5306-4b10-bcbe-a1579d589446"
* }
*
* @apiUse DefaultException
*
* @description : 新增
* ---------------------------------
* @author : zj
* @since : Create in 2022-05-31
*/
@PostMapping(value = "/create")
public ResponseData create(@RequestBody QuestionQa questionQa) {
return success(questionQaService.create(questionQa));
}
}

View File

@@ -0,0 +1,28 @@
package com.wx.application.core.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-09-23
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_graph_case")
public class GraphCase extends BaseEntity<Long> {
private String name;
private String comment;
private String ontologyId;
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.core.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-08-02
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_graph_task")
public class GraphTask extends BaseEntity<Long> {
private String space;
private String fileName;
private Integer status;
}

View File

@@ -0,0 +1,34 @@
package com.wx.application.core.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-03-14
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_ontology")
public class Ontology extends BaseEntity<Long> {
private String name;
private String description;
/**
* 数据源类型
* 1 : 自定义本体
* 2 : 标注系统本体
* 3 : 实例图谱空间
*/
private Integer sourceType;
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.core.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_ontology_concept")
public class OntologyConcept extends BaseEntity<Long> {
private Long ontologyId;
private String ownId;
private String label;
private String parentId;
}

View File

@@ -0,0 +1,48 @@
package com.wx.application.core.entity;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import com.wx.application.nebula.graph.enums.DataType;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_ontology_field")
public class OntologyField extends BaseEntity<Long> {
private Long ontologyId;
private String field;
private DataType type;
private Integer len;
/**
* 单个属性的描述
*/
private String comment;
private Long parentId;
/**
* 对应OntologyConcept 的ownId集合
*/
@TableField(exist = false)
private List<String> conceptIds;
}

View File

@@ -0,0 +1,37 @@
package com.wx.application.core.entity;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_ontology_relation")
public class OntologyRelation extends BaseEntity<Long> {
private Long ontologyId;
private String label;
private Long parentId;
private Boolean arrow = false;
@TableField(exist = false)
private List<String> srcIds;
@TableField(exist = false)
private List<String> dctIds;
}

View File

@@ -0,0 +1,28 @@
package com.wx.application.core.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2022-05-31
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName("dn_question_qa")
public class QuestionQa extends BaseEntity<Long> {
private String question;
private String answer;
}

View File

@@ -0,0 +1,28 @@
package com.wx.application.core.entity;
import com.wx.application.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author zj
* @since 2021-11-24
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class RiskUser extends BaseEntity<Long> {
private String username;
private String realname;
private String password;
private String type;
}

View File

@@ -0,0 +1,20 @@
package com.wx.application.core.mapper;
import com.wx.application.core.entity.GraphCase;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-09-23
*/
@Repository
public interface GraphCaseMapper extends BaseMapper<GraphCase> {
void deleteById(Long id);
}

View File

@@ -0,0 +1,20 @@
package com.wx.application.core.mapper;
import com.wx.application.core.entity.GraphTask;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-08-02
*/
@Repository
public interface GraphTaskMapper extends BaseMapper<GraphTask> {
int countBySpaceAndStauts(@Param("space") String space);
}

View File

@@ -0,0 +1,25 @@
package com.wx.application.core.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wx.application.core.entity.OntologyConcept;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Repository
public interface OntologyConceptMapper extends BaseMapper<OntologyConcept> {
int countByOntologyId(@Param("ontologyId") Long ontologyId);
int countChildbyid(@Param("parentId") String parentId);
OntologyConcept findByOntologyIdAndLabel(@Param("ontologyId") Long ontologyId,
@Param("label") String label);
}

View File

@@ -0,0 +1,23 @@
package com.wx.application.core.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wx.application.core.entity.OntologyField;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Repository
public interface OntologyFieldMapper extends BaseMapper<OntologyField> {
int countByOntologyId(@Param("ontologyId") Long ontologyId);
OntologyField findByOntologyIdAndLabel(@Param("ontologyId") Long ontologyId,
@Param("field") String field);
}

View File

@@ -0,0 +1,18 @@
package com.wx.application.core.mapper;
import com.wx.application.core.entity.Ontology;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-03-14
*/
@Repository
public interface OntologyMapper extends BaseMapper<Ontology> {
}

View File

@@ -0,0 +1,25 @@
package com.wx.application.core.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wx.application.core.entity.OntologyRelation;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Repository
public interface OntologyRelationMapper extends BaseMapper<OntologyRelation> {
int countByOntologyId(@Param("ontologyId") Long ontologyId);
OntologyRelation findByOntologyIdAndLabel(@Param("ontologyId") Long ontologyId,
@Param("label") String label);
}

View File

@@ -0,0 +1,18 @@
package com.wx.application.core.mapper;
import com.wx.application.core.entity.QuestionQa;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2022-05-31
*/
@Repository
public interface QuestionQaMapper extends BaseMapper<QuestionQa> {
}

View File

@@ -0,0 +1,18 @@
package com.wx.application.core.mapper;
import com.wx.application.core.entity.RiskUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zj
* @since 2021-11-24
*/
@Repository
public interface RiskUserMapper extends BaseMapper<RiskUser> {
}

View File

@@ -0,0 +1,57 @@
package com.wx.application.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.GraphCase;
import com.wx.application.core.mapper.GraphCaseMapper;
import com.wx.application.nebula.graph.bean.NebulaSpace;
import com.wx.application.nebula.graph.service.NebulaOperateService;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-09-23
*/
/*@Slf4j*/
@Service("coreGraphCaseService")
@Transactional
public class GraphCaseService extends BaseService<GraphCase, GraphCaseMapper> {
@Autowired
GraphCaseMapper baseMapper;
@Autowired
NebulaOperateService nebulaOperateService;
/**
* 创建工作空间
*/
public NebulaSpace createGraphCase(GraphCase graphCase) {
create(graphCase);
NebulaSpace e = new NebulaSpace();
e.setName(graphCase.getName());
e.setComment(graphCase.getComment());
nebulaOperateService.createSpace(e);
return e;
}
public void removeGraphCase(Long id) {
GraphCase graphCase = getOne(id);
if(graphCase != null) {
nebulaOperateService.dropSpace(graphCase.getName());
baseMapper.deleteById(id);
}
}
}

View File

@@ -0,0 +1,32 @@
package com.wx.application.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.GraphTask;
import com.wx.application.core.mapper.GraphTaskMapper;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-08-02
*/
/*@Slf4j*/
@Service("coreGraphTaskService")
@Transactional
public class GraphTaskService extends BaseService<GraphTask, GraphTaskMapper> {
@Autowired
GraphTaskMapper baseMapper;
public int countBySpaceAndStauts(String space) {
return baseMapper.countBySpaceAndStauts(space);
}
}

View File

@@ -0,0 +1,217 @@
package com.wx.application.core.service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.OntologyConcept;
import com.wx.application.core.mapper.OntologyConceptMapper;
import com.wx.application.core.mapper.OntologyFieldMapper;
import com.wx.application.core.mapper.OntologyRelationMapper;
import com.wx.application.nebula.graph.base.Generators;
import com.wx.application.nebula.graph.bean.ModelVertex;
import com.wx.application.nebula.graph.service.NebulaModelService;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Slf4j
@Service("coreOntologyConceptService")
@Transactional
public class OntologyConceptService extends BaseService<OntologyConcept, OntologyConceptMapper> {
@Autowired
OntologyConceptMapper baseMapper;
@Autowired
OntologyFieldMapper ontologyFieldMapper;
@Autowired
OntologyRelationMapper ontologyRelationMapper;
@Autowired
NebulaModelService nebulaModelService;
/**
* 新增概念
*/
public OntologyConcept createOntologyConcept(OntologyConcept ontologyConcept) {
String ownId = ontologyConcept.getOwnId();
/**
* 验证label
*/
OntologyConcept has = baseMapper.findByOntologyIdAndLabel(ontologyConcept.getOntologyId(),
ontologyConcept.getLabel());
if(has != null && has.getId() > 0) {
return has;
}
if(StringUtils.isBlank(ontologyConcept.getOwnId())) {
ownId = Generators.vid(ontologyConcept.getLabel());
ownId = Generators.ontologyVid(ontologyConcept.getOntologyId() , ownId);
ontologyConcept.setOwnId(ownId);
}
create(ontologyConcept);
/**
* 将概念加入图谱中
*/
ModelVertex mx = new ModelVertex();
mx.setOntologyId(ontologyConcept.getOntologyId());
mx.setLabel(ontologyConcept.getLabel());
mx.setTagName(Generators.tagname(mx.getLabel()));
mx.setVid(ownId);
nebulaModelService.insertModelVertex(mx);
return ontologyConcept;
}
public Boolean modifyOntologyConcept(OntologyConcept ontologyConcept) {
if(StringUtils.isBlank(ontologyConcept.getOwnId())
|| StringUtils.isBlank(ontologyConcept.getLabel())) {
return false;
}
QueryWrapper<OntologyConcept> wrapper = new QueryWrapper();
wrapper.eq("own_id", ontologyConcept.getOwnId());
OntologyConcept oct = baseMapper.selectOne(wrapper);
oct.setLabel(ontologyConcept.getLabel());
/**
* 将概念加入图谱中
*/
Boolean flag = false;
if(flag = modify(oct)) {
ModelVertex mx = new ModelVertex();
mx.setOntologyId(oct.getOntologyId());
mx.setLabel(oct.getLabel());
mx.setTagName(Generators.tagname(mx.getLabel()));
mx.setVid(oct.getOwnId());
nebulaModelService.insertModelVertex(mx);
}
return flag;
}
/**
* 递归删除
*/
public Boolean deleteOntologyConcept(Long id) {
try {
if(id == null) {
return false;
}
OntologyConcept oct = getOne(id);
QueryWrapper<OntologyConcept> wrapper = new QueryWrapper();
wrapper.eq("parent_id", oct.getOwnId()).or().eq("id", id);
List<OntologyConcept> childs = baseMapper.selectList(wrapper);
baseMapper.delete(wrapper);
List<String> vids = childs.stream().map(OntologyConcept::getOwnId).collect(Collectors.toList());
/**
* 删除图谱中的点
*/
nebulaModelService.deleteModelVertexs(vids);
if(childs != null) {
for(OntologyConcept ot : childs) {
deleteOntologyConcept(ot.getId());
}
}
} catch (Exception e) {
log.info("{}",e);
return false;
}
return true;
}
/**
* 根据本体id统计
* @param ontologyId
* @return
*/
public JSONObject countAllByOntologyId(Long ontologyId) {
int conceptc = baseMapper.countByOntologyId(ontologyId);
int fieldc = ontologyFieldMapper.countByOntologyId(ontologyId);
int relationc = ontologyRelationMapper.countByOntologyId(ontologyId);
JSONObject result = new JSONObject();
result.set("conceptc", conceptc);
result.set("fieldc", fieldc);
result.set("relationc", relationc);
return result;
}
public Integer countChildbyid(Long id) {
if(id == null) {
return 0;
}
OntologyConcept oct = getOne(id);
if(oct == null) {
return 0;
}
Integer c = baseMapper.countChildbyid(oct.getOwnId());
return c;
}
public List<OntologyConcept> findWithParents(String ownId) {
QueryWrapper<OntologyConcept> wrapper = new QueryWrapper();
wrapper.eq("own_id", ownId);
OntologyConcept own = baseMapper.selectOne(wrapper);
List<OntologyConcept> concepts = null;
if(own != null) {
concepts = new ArrayList<>();
findWithParents(own, concepts);
}
return concepts;
}
/**
* 递归
* 查询当前节点的值属性,包含继承的值属性
*/
public void findWithParents(OntologyConcept own, List<OntologyConcept> concepts) {
QueryWrapper<OntologyConcept> wrapper = new QueryWrapper();
wrapper.eq("own_id", own.getParentId());
OntologyConcept pa = baseMapper.selectOne(wrapper);
if(pa != null) {
concepts.add(pa);
findWithParents(pa, concepts);
}
}
}

View File

@@ -0,0 +1,248 @@
package com.wx.application.core.service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.OntologyField;
import com.wx.application.core.mapper.OntologyFieldMapper;
import com.wx.application.nebula.graph.bean.ModelVertex;
import com.wx.application.nebula.graph.bean.NebulaField;
import com.wx.application.nebula.graph.query.NebulaNode;
import com.wx.application.nebula.graph.service.NebulaModelService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Slf4j
@Service("coreOntologyFieldService")
@Transactional
public class OntologyFieldService extends BaseService<OntologyField, OntologyFieldMapper> {
@Autowired
OntologyFieldMapper baseMapper;
@Autowired
NebulaModelService nebulaModelService;
public OntologyField createOntologyField(OntologyField ontologyField) {
/**
* 验证label
*/
OntologyField has = baseMapper.findByOntologyIdAndLabel(ontologyField.getOntologyId(),
ontologyField.getField());
if(has != null && has.getId() > 0) {
return has;
}
return create(ontologyField);
}
/**
* 根据选择的概念添加属性
* @param OntologyField
*/
public void createConceptField(OntologyField ontologyField) {
Long id = ontologyField.getId();
OntologyField field = getOne(id);
if(field == null) {
return;
}
List<String> vids = ontologyField.getConceptIds();
/**
* 先获得本体的所有概念
*/
List<NebulaNode> nodes = nebulaModelService.findNodesByOntologyId(field.getOntologyId());
for(NebulaNode node : nodes) {
List<NebulaField> fields = null;
NebulaField nf = null;
String operate = null;
int findex = -1;
JSONObject properties = node.getProperties();
JSONArray fieldsnapshot = properties.getJSONArray("nebulafieldsnapshot");
ModelVertex vertex = properties.toBean(ModelVertex.class);
if(vids.contains(node.getVid())) {
operate = "add";
}
/**
* 如果当前概念包括值属性
*/
if(fieldsnapshot != null) {
fields = fieldsnapshot.toList(NebulaField.class);
List<String> fieldnames = fields.stream().map(NebulaField::getField).collect(Collectors.toList());
if(fieldnames.contains(field.getField())) {
operate = vids.contains(node.getVid())?"have":"remove";
findex = fieldnames.indexOf(field.getField());
}
}
if("add".equals(operate) || "remove".equals(operate)) {
if(fields == null) {
fields = new ArrayList<>();
}
switch (operate) {
case "add":
BeanUtil.copyProperties(field, nf = new NebulaField());
fields.add(nf);
break;
case "remove":
if(findex > -1) {
fields.remove(findex);
}
break;
default:
break;
}
vertex.setFields(fields);
vertex.setVid(node.getVid());
nebulaModelService.insertModelVertex(vertex);
}
}
}
public void deleteConceptField(Long id) {
OntologyField field = getOne(id);
if(field == null) {
return;
}
/**
* 先获得本体的所有概念
*/
List<NebulaNode> nodes = nebulaModelService.findNodesByOntologyId(field.getOntologyId());
List<NebulaField> fields = null;
for(NebulaNode node : nodes) {
int findex = -1;
String operate = null;
JSONObject properties = node.getProperties();
JSONArray fieldsnapshot = properties.getJSONArray("nebulafieldsnapshot");
ModelVertex vertex = properties.toBean(ModelVertex.class);
/**
* 如果当前概念包括值属性
*/
if(fieldsnapshot != null) {
fields = fieldsnapshot.toList(NebulaField.class);
List<String> fieldnames = fields.stream().map(NebulaField::getField).collect(Collectors.toList());
if(fieldnames.contains(field.getField())) {
operate = "remove";
findex = fieldnames.indexOf(field.getField());
}
}
if(StringUtils.isNotBlank(operate)) {
switch (operate) {
case "remove":
if(findex > -1) {
fields.remove(findex);
}
break;
default:
break;
}
vertex.setFields(fields);
vertex.setVid(node.getVid());
nebulaModelService.insertModelVertex(vertex);
}
}
remove(id);
}
public void modifyOntologyField(OntologyField ontologyField) {
Long id = ontologyField.getId();
OntologyField field = getOne(id);
if(field == null) {
return;
}
/**
* 先获得本体的所有概念
*/
List<NebulaNode> nodes = nebulaModelService.findNodesByOntologyId(field.getOntologyId());
List<NebulaField> fields = null;
for(NebulaNode node : nodes) {
int findex = -1;
String operate = null;
JSONObject properties = node.getProperties();
JSONArray fieldsnapshot = properties.getJSONArray("nebulafieldsnapshot");
ModelVertex vertex = properties.toBean(ModelVertex.class);
/**
* 如果当前概念包括值属性
*/
if(fieldsnapshot != null) {
fields = fieldsnapshot.toList(NebulaField.class);
List<String> fieldnames = fields.stream().map(NebulaField::getField).collect(Collectors.toList());
if(fieldnames.contains(field.getField())) {
operate = "modify";
findex = fieldnames.indexOf(field.getField());
}
}
if(StringUtils.isNotBlank(operate)) {
switch (operate) {
case "modify":
if(findex > -1) {
fields.remove(findex);
}
NebulaField nf = null;
BeanUtil.copyProperties(ontologyField, nf = new NebulaField());
fields.add(nf);
break;
default:
break;
}
vertex.setFields(fields);
vertex.setVid(node.getVid());
nebulaModelService.insertModelVertex(vertex);
}
}
modify(ontologyField);
}
}

View File

@@ -0,0 +1,208 @@
package com.wx.application.core.service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.OntologyRelation;
import com.wx.application.core.mapper.OntologyRelationMapper;
import com.wx.application.nebula.graph.base.Generators;
import com.wx.application.nebula.graph.bean.ModelEdgeLine;
import com.wx.application.nebula.graph.bean.NebulaEdgeLine;
import com.wx.application.nebula.graph.query.NebulaRelation;
import com.wx.application.nebula.graph.service.NebulaModelService;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-09-25
*/
@Slf4j
@Service("coreOntologyRelationService")
@Transactional
public class OntologyRelationService extends BaseService<OntologyRelation, OntologyRelationMapper> {
@Autowired
OntologyRelationMapper baseMapper;
@Autowired
NebulaModelService nebulaModelService;
public OntologyRelation createOntologyRelation(OntologyRelation ontologyRelation) {
/**
* 验证label
*/
OntologyRelation has = baseMapper.findByOntologyIdAndLabel(ontologyRelation.getOntologyId(),
ontologyRelation.getLabel());
if(has != null && has.getId() > 0) {
return has;
}
return create(ontologyRelation);
}
/**
* 新增对象属性
*/
public Boolean createRelations(OntologyRelation ontologyRelation) {
try {
Long id = ontologyRelation.getId();
List<String> srcIds = ontologyRelation.getSrcIds();
List<String> dstIds = ontologyRelation.getDctIds();
if(id == null) {
return false;
}
OntologyRelation orl = getOne(id);
if(orl == null) {
return false;
}
/**
* 根据label标签查询关系,目前库里已经存在的
*/
List<NebulaRelation> relations = nebulaModelService
.findRelationsByLabel(orl.getLabel());
List<NebulaRelation> newRelations = new ArrayList<>();
if(srcIds != null && dstIds != null) {
srcIds.forEach(srcId->{
dstIds.forEach(dstId->{
NebulaRelation ln = new NebulaRelation();
ln.setSrcId(srcId);
ln.setDstId(dstId);
newRelations.add(ln);
});
});
}
relations.forEach(v-> {
if(!newRelations.contains(v)) {
NebulaEdgeLine el = new NebulaEdgeLine();
el.setSrcId(v.getSrcId());
el.setDstId(v.getDstId());
nebulaModelService.deleteModelEdge(el);
} else {
newRelations.remove(v);
}
});
newRelations.forEach(v-> {
ModelEdgeLine el = new ModelEdgeLine();
el.setSrcId(v.getSrcId());
el.setDstId(v.getDstId());
el.setLabel(orl.getLabel());
el.setEdgeName(Generators.edgename(orl.getLabel()));
el.setOntologyId(orl.getOntologyId());
nebulaModelService.insertModelEdge(el);
});
} catch (Exception e) {
log.info("{}",e);
return false;
}
return true;
}
public Boolean modifyOntologyRelation(OntologyRelation ontologyRelation) {
Long id = ontologyRelation.getId();
OntologyRelation orl = getOne(id);
String oldname = orl.getLabel();
Boolean flag = false;
if(flag = modify(ontologyRelation)) {
/**
* 根据label标签查询关系
*/
List<NebulaRelation> relations = nebulaModelService
.findRelationsByLabel(oldname);
for(NebulaRelation relation : relations) {
JSONObject properties = relation.getProperties();
ModelEdgeLine el = properties.toBean(ModelEdgeLine.class);
el.setSrcId(relation.getSrcId());
el.setDstId(relation.getDstId());
el.setLabel(ontologyRelation.getLabel());
el.setEdgeName(Generators.edgename(ontologyRelation.getLabel()));
nebulaModelService.insertModelEdge(el);
}
}
return flag;
}
/**
* 递归删除
*/
public Boolean deleteOntologyRelation(Long id) {
try {
/**
* 根据id 查询所有的子项和自己
*/
QueryWrapper<OntologyRelation> wrapper = new QueryWrapper();
wrapper.eq("parent_id", id).or().eq("id", id);
List<OntologyRelation> ors = baseMapper.selectList(wrapper);
baseMapper.delete(wrapper);
List<String> names = ors.stream().map(OntologyRelation::getLabel).collect(Collectors.toList());
names.forEach(v-> {
/**
* 根据label标签查询关系
*/
List<NebulaRelation> relations = nebulaModelService
.findRelationsByLabel(v);
NebulaEdgeLine edge = null;
for(NebulaRelation r : relations) {
edge = new NebulaEdgeLine();
edge.setSrcId(r.getSrcId());
edge.setDstId(r.getDstId());
nebulaModelService.deleteModelEdge(edge);
}
});
if(ors != null) {
for(OntologyRelation ot : ors) {
if(ot.getId() == id) {
continue;
}
deleteOntologyRelation(ot.getId());
}
}
} catch (Exception e) {
log.info("{}",e);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.Ontology;
import com.wx.application.core.mapper.OntologyMapper;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-03-14
*/
/*@Slf4j*/
@Service("coreOntologyService")
@Transactional
public class OntologyService extends BaseService<Ontology, OntologyMapper> {
@Autowired
OntologyMapper baseMapper;
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.QuestionQa;
import com.wx.application.core.mapper.QuestionQaMapper;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2022-05-31
*/
/*@Slf4j*/
@Service("coreQuestionQaService")
@Transactional
public class QuestionQaService extends BaseService<QuestionQa, QuestionQaMapper> {
@Autowired
QuestionQaMapper baseMapper;
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.core.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wx.application.base.BaseService;
import com.wx.application.core.entity.RiskUser;
import com.wx.application.core.mapper.RiskUserMapper;
/**
* <p>
* 服务类
* </p>
*
* @author zj
* @since 2021-11-24
*/
/*@Slf4j*/
@Service("coreRiskUserService")
@Transactional
public class RiskUserService extends BaseService<RiskUser, RiskUserMapper> {
@Autowired
RiskUserMapper baseMapper;
}

View File

@@ -0,0 +1,27 @@
package com.wx.application.exception;
import com.wx.application.base.ErrorCodeEnum;
public class CommonException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public CommonException() {
super();
}
public CommonException(Throwable e) {
super(e.getMessage(), e);
}
public CommonException(String message) {
super(message);
}
public CommonException(ErrorCodeEnum responseCodeEnum) {
super(responseCodeEnum.toString());
}
}

View File

@@ -0,0 +1,97 @@
package com.wx.application.exception;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import com.wx.application.base.ErrorCodeEnum;
import com.wx.application.base.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Locale;
import static com.wx.application.base.ErrorCodeEnum.PARAM_ERROR;
@ControllerAdvice
@Slf4j
@Order(1)
public class GlobalExceptionHandler {
@Autowired
private MessageSource messageSource;
/**
* 全局统一异常处理
*/
@ExceptionHandler(value = {CommonException.class, Exception.class})
@ResponseBody
public ResponseData handler(Exception e) {
// 获取local国际化信息
Locale locale = LocaleContextHolder.getLocale();
// 国际化message信息
String msg = null;
String errCode = null;
try {
errCode = e.getMessage();
msg = messageSource.getMessage(e.getMessage(), null, locale);
} catch (NoSuchMessageException ex) {
errCode = e.getClass().getSimpleName();
msg = e.getMessage();
}
log.error("全局异常捕获: {}", msg, e);
return ResponseData.ERROR(errCode, msg, null);
}
/**
* 全局统一异常处理
*/
@ExceptionHandler(value = KaptchaException.class)
@ResponseBody
public ResponseData handler(KaptchaException e) {
// 获取local国际化信息
Locale locale = LocaleContextHolder.getLocale();
// 国际化message信息
String msg = null;
String errCode = null;
try {
if (e instanceof KaptchaIncorrectException) {
errCode = "KAPTCHA_INCORRECT";
} else if (e instanceof KaptchaNotFoundException) {
errCode = "KAPTCHA_NOT_FOUND";
} else if (e instanceof KaptchaTimeoutException) {
errCode = "KAPTCHA_TIMEOUT";
} else {
errCode = "KAPTCHA_ERROR";
}
msg = messageSource.getMessage(errCode, null, locale);
} catch (NoSuchMessageException ex) {
errCode = ErrorCodeEnum.SYSTEM_ERROR.toString();
msg = e.getMessage();
}
log.error("全局异常捕获: {}", msg, e);
return ResponseData.ERROR(errCode, msg, null);
}
/**
* 全局统一异常处理
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public ResponseData handler(MethodArgumentNotValidException e) {
String errorMessage = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).reduce((s1, s2) -> s1.concat(",").concat(s2)).get();
log.error("入参异常捕获: {}", errorMessage, e);
return ResponseData.ERROR(PARAM_ERROR, errorMessage, null);
}
}

View File

@@ -0,0 +1,63 @@
package com.wx.application.filter;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.wx.application.configuration.annotation.AspectOff;
import com.wx.application.constant.CONSTANT;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
@Slf4j
@Order(5)
@ControllerAdvice()
public class GlobalRequestBodyAdvice implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return !methodParameter.getMethod().isAnnotationPresent(AspectOff.class);
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
return new HttpInputMessage() {
@SneakyThrows
@Override
public InputStream getBody() {
// 获取 json 字符串
@Cleanup ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
IoUtil.copy(httpInputMessage.getBody(), byteArrayOutputStream);
String bodyStr = new String(byteArrayOutputStream.toByteArray());
log.info("请求信息: url: {} header: {} , body: {}", MDC.get(CONSTANT.REQUEST_URL), JSON.toJSONString(httpInputMessage.getHeaders().entrySet()), bodyStr);
return IoUtil.toStream(byteArrayOutputStream.toByteArray());
}
@Override
public HttpHeaders getHeaders() {
return httpInputMessage.getHeaders();
}
};
}
@Override
public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return o;
}
@Override
public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return o;
}
}

View File

@@ -0,0 +1,46 @@
package com.wx.application.filter;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wx.application.base.ResponseData;
import com.wx.application.configuration.annotation.AspectOff;
import com.wx.application.constant.CONSTANT;
import lombok.SneakyThrows;
@Order(5)
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Autowired
ObjectMapper objectMapper;
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return !methodParameter.getMethod().isAnnotationPresent(AspectOff.class);
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//log.info("返回信息: header: {} , body: {}", JSON.toJSONString(serverHttpResponse.getHeaders().entrySet()), objectMapper.writeValueAsString(o));
serverHttpResponse.getHeaders().add(CONSTANT.X_REQ_ID, MDC.get(CONSTANT.REQUEST_ID_KEY));
if (o instanceof ResponseData) {
//统一回填header信息
ResponseData responseData = (ResponseData) o;
responseData.setRequestId(MDC.get(CONSTANT.REQUEST_ID_KEY));
MDC.clear();
return responseData;
}
MDC.clear();
return o;
}
}

View File

@@ -0,0 +1,120 @@
package com.wx.application.filter;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.alibaba.fastjson.JSON;
import com.wx.application.base.BaseController;
import com.wx.application.base.ErrorCodeEnum;
import com.wx.application.base.ResponseData;
import com.wx.application.configuration.FilterIgnorePropertiesConfig;
import com.wx.application.constant.CONSTANT;
import com.wx.application.util.JwtUtils;
/**
* jwt 拦截过滤器
*
* @comment
*/
@WebFilter(filterName = "jwtFilter", urlPatterns = "/*")
@Order(2)
//@Slf4j
public class JwtAuthFilter extends BaseController implements Filter {
@Autowired
private FilterIgnorePropertiesConfig ignores;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
filterConfig.getServletContext());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String uri = httpRequest.getRequestURI();
String token = httpRequest.getHeader(CONSTANT.TOKEN_NAME);
requestInitialized(httpRequest);
ResponseData errorMsg = null;
try {
if (matchIgnore(uri)) {
chain.doFilter(request, response);
return;
} else if (HttpMethod.OPTIONS.name().equals(httpRequest.getMethod())) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
chain.doFilter(request, response);
return;
} else {
if (StringUtils.isEmpty(token)) {
errorMsg = error(ErrorCodeEnum.UNAUTHORIZED);
return;
}
//检查jwt有效性
if (!JwtUtils.checkTokenExpired(token)) {
errorMsg = error(ErrorCodeEnum.AUTHORIZATION_EXPIRED);
return;
}
chain.doFilter(request, response);
return;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (null != errorMsg) {
errorMsg.setRequestId(MDC.get(CONSTANT.REQUEST_ID_KEY));
httpResponse.setContentType("application/json;charset=utf-8");
httpResponse.getWriter().write(JSON.toJSONString(errorMsg));
}
}
}
@Override
public void destroy() {
}
/**
* 初始化request 记录全局唯一的标识
*/
public void requestInitialized(HttpServletRequest request) {
String requestId = null;
if (request != null) {
requestId = request.getHeader(CONSTANT.X_REQ_ID);
}
if (org.apache.commons.lang.StringUtils.isBlank(requestId)) {
requestId = UUID.randomUUID().toString();
}
MDC.put(CONSTANT.REQUEST_ID_KEY, requestId);
MDC.put(CONSTANT.REQUEST_URL, request.getRequestURI());
}
private boolean matchIgnore(String uri) {
AntPathMatcher pm = new AntPathMatcher();
boolean match = ignores.getUrls().stream().anyMatch(v -> pm.match(v, uri));
return match;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
package com.wx.application.nebula.graph.base;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.wx.application.nebula.graph.bean.NebulaField;
public class FieldsUtils {
/**
* 字段处理属性逻辑
* @param fields
* @return
*/
public static String toStringFields(List<NebulaField> fields) {
if(fields == null || fields.size() == 0) {
return "";
}
List<String> list = new ArrayList<>();
if(fields != null) {
for(NebulaField fn : fields) {
list.add(toStringField(fn));
}
}
return StringUtils.join(list.toArray(), ",");
}
public static String toStringField(NebulaField field) {
String ft = field.getField() + " " + field.getType().name();
if(StringUtils.isNotBlank(field.getComment())) {
ft = ft + " COMMENT " + "\""+ field.getComment() +"\"";
}
return ft;
}
public static String toStringFieldNames(List<NebulaField> fields) {
if(fields == null) {
return "";
}
List<String> list = new ArrayList<>();
for(NebulaField fn : fields) {
list.add(fn.getField());
}
return StringUtils.join(list.toArray(), ",");
}
public static String toIndexFields(List<NebulaField> fields) {
if(fields == null) {
return "";
}
List<String> list = new ArrayList<>();
for(NebulaField fn : fields) {
list.add(toStringFieldIndex(fn.getField(),fn.getLen()));
}
return StringUtils.join(list.toArray(), ",");
}
public static String toStringFieldIndex(String fieldName,Integer len) {
if(len != null && len > 0) {
return fieldName + "(" + len + ")";
}
return fieldName;
}
}

View File

@@ -0,0 +1,54 @@
package com.wx.application.nebula.graph.base;
import cn.hutool.core.util.HashUtil;
public class Generators {
private final static String tag = "tag_";
private final static String edge = "edge_";
private final static String tagindex = "tagindex_";
private final static String edgeindex = "edgeindex_";
private final static String field = "field_";
private final static String name = "名称,姓名,name";
public static String tagname(String label) {
return tag + HashUtil.fnvHash(label);
}
public static String indextagname(String name) {
return tagindex + name;
}
public static String indexedgename(String name) {
return edgeindex + name;
}
public static String edgename(String label) {
return edge + HashUtil.fnvHash(label);
}
public static String fieldname(String label) {
if(name.contains(label)) {
return "name";
}
return field + HashUtil.fnvHash(label);
}
public static String vid(String label) {
return "" + HashUtil.fnvHash(label);
}
/**
* 本体空间所需要得id
* @param ontologyId
* @param label
* @return
*/
public static String ontologyVid(Long ontologyId, String vid) {
return ontologyId + "_" + vid;
}
}

View File

@@ -0,0 +1,93 @@
package com.wx.application.nebula.graph.base;
/**
* 语句模板
*/
public interface GqlTemplate {
final static String CREATESPACE = "CREATE SPACE IF NOT EXISTS {}(vid_type = {}({})) COMMENT =\"{}\"";
final static String SHOWSPACES = "SHOW SPACES";
final static String USESPACE = "USE {};";
final static String DROPSPACE = "DROP SPACE IF EXISTS {}";
final static String DESCSPACE = "DESC SPACE {}";
final static String CREATETAG = "CREATE TAG IF NOT EXISTS {} ({}) COMMENT =\"{}\"";
final static String DROPTAG = "DROP TAG IF EXISTS {}";
final static String ALTERADDTAG = "ALTER TAG {} ADD ({})";
final static String ALTERDROPTAG = "ALTER TAG {} DROP ({})";
final static String ALTERCHANGETAG = "ALTER TAG {} CHANGE ({})";
final static String SHOWTAGS = "SHOW TAGS";
final static String SHOWCREATETAG = "SHOW create tag {}";
final static String DESCRIBETAG = "DESCRIBE TAG {}";
final static String CREATEEDGE = "CREATE EDGE IF NOT EXISTS {}({}) COMMENT =\"{}\"";
final static String DROPEDGE = "DROP EDGE IF EXISTS {}";
final static String ALTERADDEDGE = "ALTER EDGE {} ADD ({})";
final static String ALTERDROPEDGE = "ALTER EDGE {} DROP ({})";
final static String ALTERCHANGEEDGE = "ALTER EDGE {} CHANGE ({})";
final static String SHOWEDGES = "SHOW EDGES";
final static String DESCRIBEEDGE = "DESCRIBE EDGE {}";
final static String SHOWCREATEEDGE = "SHOW create edge {}";
final static String CREATEINDEX = "CREATE {} INDEX IF NOT EXISTS {} on {}({}) COMMENT \"{}\"";
final static String SHOWINDEX = "SHOW {} INDEXES;";
final static String DROPINDEX = "DROP {} INDEX {};";
final static String DELETEVERTEX = "DELETE VERTEX '{}' WITH EDGE;";
final static String INSERTVERTEX = "INSERT VERTEX {} ({}) VALUES {}";
final static String DELETEEDGEDATA = "DELETE EDGE {} {}->{}";
final static String INSERTDGEDATA = "INSERT EDGE {} ({}) VALUES {}";
final static String NODESBYVID = "match(v) where id(v)=={} return v";
final static String NODESBYVIDS = "FETCH PROP ON {} {} YIELD vertex AS v";
final static String RELATIONSBYVIDS = "FETCH PROP ON {} {} YIELD edge AS e";
final static String ONERELATIONBYID = "MATCH p=(n1)-->(n2) where id(n1)=={} RETURN p";
final static String ONERELATIONBYSRCIDANDDCTID = "MATCH p=(n1)-->(n2) where id(n1)=={} and id(n2)=={} RETURN p";
final static String PAGING =" | limit {},{}";
final static String MATCHVERTEXSNGQL = "MATCH (n) RETURN n skip {} limit {}";
final static String LOOKUPEDGESNGQL = "LOOKUP ON {} YIELD edge as e";
final static String LOOKUPVERTEXSNGQL = "LOOKUP ON {} YIELD vertex as e";
final static String MATCHVERTEXBYWHERESNGQL = "MATCH (v:{}) {} RETURN v skip {} limit {}";
/**
* 根据点的id集合删除点
*/
final static String DELETEVERTEXBYVIDS = "FETCH PROP ON {} {} YIELD id(vertex) as id | DELETE VERTEX $-.id WITH EDGE";
/**
* 根据条件管道删除点
*/
final static String DELETEVERTEXCONDUIT = "LOOKUP ON {} YIELD id(vertex) as id | DELETE VERTEX $-.id WITH EDGE";
/**
* 根据条件统计点
*/
final static String COUNTVERTEXS = "LOOKUP ON {} YIELD id(vertex) | YIELD COUNT(*) AS ct";
/**
* 根据条件统计边
*/
final static String COUNTEDGES = "LOOKUP ON {} YIELD edge AS e | YIELD COUNT(*) AS ct";
/**
* 根据图空间统计
*/
final static String SUBMITJOBSTATS = "SUBMIT JOB STATS";
final static String SHOWSTATS = "SHOW STATS";
final static String STOPJOB = "STOP JOB {}";
}

View File

@@ -0,0 +1,43 @@
/*package com.wx.application.nebula.graph.base;
import java.util.Arrays;
import java.util.List;
import com.vesoft.nebula.client.graph.NebulaPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NebulaGraphClient {
NebulaPool pool;
public void nebulaPool() {
pool = new NebulaPool();
try {
NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
nebulaPoolConfig.setMaxConnSize(200);
nebulaPoolConfig.setIdleTime(5000);
nebulaPoolConfig.setWaitTime(5000);
List<HostAddress> addresses = Arrays.asList(new HostAddress("47.103.128.32", 9669));
pool.init(addresses, nebulaPoolConfig);
} catch (Exception e) {
log.info("{}" ,e);
}
}
public Session getSession() throws Exception {
return pool.getSession("root", "123456", false);
}
public void returnSession(Session session) {
session.release();
}
}
*/

View File

@@ -0,0 +1,19 @@
/*package com.wx.application.nebula.graph.base;
import javax.annotation.PostConstruct;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NebulaGraphConfig {
@Bean
@PostConstruct
public NebulaGraphClient nebulaGraphClient() {
NebulaGraphClient nebulaGraphClient = new NebulaGraphClient();
nebulaGraphClient.nebulaPool();
return nebulaGraphClient;
}
}
*/

View File

@@ -0,0 +1,282 @@
package com.wx.application.nebula.graph.base;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.vesoft.nebula.client.graph.data.Node;
import com.vesoft.nebula.client.graph.data.PathWrapper;
import com.vesoft.nebula.client.graph.data.Relationship;
import com.vesoft.nebula.client.graph.data.ResultSet;
import com.vesoft.nebula.client.graph.data.ValueWrapper;
import com.wx.application.nebula.graph.query.NebulaModel;
import com.wx.application.nebula.graph.query.NebulaNode;
import com.wx.application.nebula.graph.query.NebulaRelation;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public class ResultSetUtils {
/**
* 结果集打印 Path
* @param resultSet
* @throws UnsupportedEncodingException
*/
public static NebulaModel printResultPath(ResultSet resultSet) {
Set<NebulaNode> ns = new HashSet<>();
Set<NebulaRelation> rls = new HashSet<>();
try {
NebulaNode node = null;
NebulaRelation relation = null;
for (int i = 0; i<resultSet.rowsSize(); i++) {
ResultSet.Record record = resultSet.rowValues(i);
for (ValueWrapper value : record.values()) {
if (value.isPath()) {
/**
* 处理节点
*/
PathWrapper pw = value.asPath();
List<Node> nodes = pw.getNodes();
for(Node nd : nodes) {
List<String> labels = nd.labels();
node = new NebulaNode();
node.setVid(nd.getId().asString());
node.setLabels(labels.get(0));
node.setProperties(nd.properties(labels.get(0)));
/**
* 处理快照
*/
printnebulafieldsnapshot(node.getProperties());
ns.add(node);
}
/**
* 处理关系
*/
List<Relationship> rs = pw.getRelationships();
for(Relationship r:rs) {
relation = new NebulaRelation();
relation.setSrcId(r.srcId().asString());
relation.setDstId(r.dstId().asString());
relation.setEdgeName(r.edgeName());
relation.setProperties(r.properties());
/**
* 处理快照
*/
printnebulafieldsnapshot(relation.getProperties());
rls.add(relation);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
NebulaModel ml = new NebulaModel();
ml.setNodes(new ArrayList<>(ns));
ml.setRelations(new ArrayList<>(rls));
return ml;
}
/**
* 结果集打印Vertex
* @param resultSet
* @throws UnsupportedEncodingException
*/
public static List<NebulaNode> printResultVertex(ResultSet resultSet) {
List<NebulaNode> ns = new ArrayList<>();
try {
NebulaNode node = null;
for (int i = 0; i<resultSet.rowsSize(); i++) {
ResultSet.Record record = resultSet.rowValues(i);
for (ValueWrapper value : record.values()) {
if (value.isVertex()) {
/**
* 处理节点
*/
Node nd = value.asNode();
List<String> labels = nd.labels();
node = new NebulaNode();
node.setVid(nd.getId().asString());
node.setLabels(labels.get(0));
node.setProperties(nd.properties(labels.get(0)));
/**
* 处理快照
*/
printnebulafieldsnapshot(node.getProperties());
ns.add(node);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ns;
}
/**
* 结果集打印Vertex
* @param resultSet
* @throws UnsupportedEncodingException
*/
public static List<NebulaRelation> printResultRelation(ResultSet resultSet) {
List<NebulaRelation> ns = new ArrayList<>();
try {
for (int i = 0; i<resultSet.rowsSize(); i++) {
ResultSet.Record record = resultSet.rowValues(i);
for (ValueWrapper value : record.values()) {
if (value.isEdge()) {
/**
* 处理关系
*/
Relationship r = value.asRelationship();
NebulaRelation relation = new NebulaRelation();
relation.setSrcId(r.srcId().asString());
relation.setDstId(r.dstId().asString());
relation.setEdgeName(r.edgeName());
relation.setProperties(r.properties());
/**
* 处理快照
*/
printnebulafieldsnapshot(relation.getProperties());
ns.add(relation);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ns;
}
/**
* 结果集打印Vertex
* @param resultSet
* @throws UnsupportedEncodingException
*/
public static List<JSONObject> printResultObject(ResultSet resultSet) {
List<JSONObject> ns = new ArrayList<>();
try {
List<String> colNames = resultSet.keys();
for (int i = 0; i<resultSet.rowsSize(); i++) {
ResultSet.Record record = resultSet.rowValues(i);
int k = 0;
for (ValueWrapper value : record.values()) {
JSONObject obj = new JSONObject();
String key = colNames.get(k);
if (value.isList()) {
List<Object> list = new ArrayList<>();
for (ValueWrapper fn : value.asList()) {
list.add(printValueWrapper(fn));
}
obj.set(key, list);
} else if (value.isSet()) {
List<Object> list = new ArrayList<>();
for (ValueWrapper fn : value.asSet()) {
list.add(printValueWrapper(fn));
}
obj.set(key, list);
} else if (value.isMap()) {
obj.set(key, value.asMap());
} else {
obj.set(key, printValueWrapper(value));
}
k++;
ns.add(obj);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ns;
}
public static List<JSONObject> printResultObject(ResultSet resultSet,Integer split) {
List<JSONObject> ots = printResultObject(resultSet);
int i = 0;
List<JSONObject> rs = new ArrayList<>();
JSONObject jt = null;
for(JSONObject fn : ots) {
if(i % split == 0) {
jt = new JSONObject();
rs.add(jt);
}
JSONObject item = new JSONObject();
for(String ky:fn.keySet()) {
item.set(ky.toLowerCase(), fn.get(ky));
}
jt.putAll(item);
i++;
}
return rs;
}
public static void printnebulafieldsnapshot(JSONObject properties) {
/**
* 快照转换
*/
properties.forEach((k,v)-> {
if(v instanceof String) {
String snapshot = properties.getStr(k);
if(JSONUtil.isTypeJSONArray(snapshot)) {
properties.set(k, JSONUtil.parseArray(snapshot));
} else if (JSONUtil.isTypeJSONObject(snapshot)) {
properties.set(k, JSONUtil.parseObj(snapshot));
}
}
});
}
public static Object printValueWrapper(ValueWrapper value) {
try {
if (value.isLong()) {
return value.asLong();
} else if (value.isBoolean()) {
return value.asBoolean();
} else if (value.isDouble()) {
return value.asDouble();
} else if (value.isString()) {
return value.asString();
} else if (value.isTime()) {
return value.asTime();
} else if (value.isDate()) {
return value.asDate();
} else if (value.isDateTime()) {
return value.asDateTime();
}
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
}

View File

@@ -0,0 +1,37 @@
package com.wx.application.nebula.graph.bean;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class ModelEdgeLine {
private Long ontologyId;
private String srcId;
private String dstId;
/**
* edge名称。必须是 英文 下划线 数字 符合属性命名规范
*/
private String edgeName;
/**
* 用于页面显示的名称
*/
private String label;
/**
* 模型对应的字段属性
*/
private List<NebulaField> fields;
/**
* 关系号 @0
*/
private Integer edgeNo = 0;
}

View File

@@ -0,0 +1,31 @@
package com.wx.application.nebula.graph.bean;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class ModelVertex {
private String vid;
private Long ontologyId;
/**
* tag名称。必须是 英文 下划线 数字 符合属性命名规范
*/
private String tagName;
/**
* 用于页面显示的名称
*/
private String label;
/**
* 模型对应的字段属性
*/
private List<NebulaField> fields;
}

View File

@@ -0,0 +1,26 @@
package com.wx.application.nebula.graph.bean;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaEdge {
/**
* edge名称。必须是 英文 下划线 数字 符合属性命名规范
*/
private String name;
/**
* 图模型标签名称
*/
private String labelName;
private String comment;
private List<NebulaField> fields;
}

View File

@@ -0,0 +1,32 @@
package com.wx.application.nebula.graph.bean;
import cn.hutool.json.JSONObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaEdgeLine {
private String edge;
private String srcId;
private String dstId;
/**
* 关系号 @0
*/
private Integer edgeNo = 0;
/**
* 关系上的相关的数据值
* {
* name:"bob"
* "arrow"true 有箭头
* false 无箭头
* }
*/
private JSONObject ob;
}

View File

@@ -0,0 +1,21 @@
package com.wx.application.nebula.graph.bean;
import com.wx.application.nebula.graph.enums.DataType;
import lombok.Data;
@Data
public class NebulaField {
private String field;
private DataType type;
private Integer len;
/**
* 单个属性的描述
*/
private String comment;
}

View File

@@ -0,0 +1,26 @@
package com.wx.application.nebula.graph.bean;
import java.util.List;
import com.wx.application.nebula.graph.enums.IndexType;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 索引创建
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaIndex {
private String onName;
private String name;
private IndexType type;
private List<NebulaField> fields;
private String comment = "";
}

View File

@@ -0,0 +1,23 @@
package com.wx.application.nebula.graph.bean;
import com.wx.application.nebula.graph.enums.VidType;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaSpace {
private String name;
/**
* 中午描述
*/
private String comment;
private Integer vidLen = 64;
private VidType vidType = VidType.FIXED_STRING;
}

View File

@@ -0,0 +1,29 @@
package com.wx.application.nebula.graph.bean;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 表bean
* @author zj
*
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaTag {
/**
* tag名称。必须是 英文 下划线 数字 符合属性命名规范
*/
private String name;
/**
* tag的描述
*/
private String comment;
private List<NebulaField> fields;
}

View File

@@ -0,0 +1,34 @@
package com.wx.application.nebula.graph.bean;
import cn.hutool.json.JSONObject;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 点bean
* @author zj
*
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaVertex {
/**
* tag
*/
private String tag;
/**
* 唯一主键
*/
private String vid;
/**
* 和相关的数据值
* {
* name:"bob"
* }
*/
private JSONObject ob;
}

View File

@@ -0,0 +1,81 @@
package com.wx.application.nebula.graph.conrtroller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.nebula.graph.service.ImportGraphInJsonService;
@RestController
@RequestMapping("/nebula_graph_import")
public class NebulaImportController extends BaseController {
@Autowired
ImportGraphInJsonService importGraphInJsonService;
/**
* 上传zip文件
* @param space
* @param file
* @return
*/
@PutMapping(value = "/uploadfile/{space}")
public ResponseData uploadFile(@PathVariable("space") String space,
@RequestParam("file") MultipartFile file) {
return success(importGraphInJsonService.uploadFile(file, space));
}
/*@Autowired
ImportGraphInExcelService importGraphService;
@Autowired
ImportSchemaService importSchemaService;
*//**
* 创建一个任务
*//*
@PutMapping(value = "/createtask/{space}")
public ResponseData createTask(@PathVariable("space") String space,
@RequestParam("file") MultipartFile file
,@RequestParam("name") String name) {
return success(importGraphService.createTask(file, space, name));
}
*//**
* 根据任务查看相关的文件信息
*//*
@GetMapping(value = "/findtaskbyid/{taskId}")
public ResponseData findTaskById(@PathVariable("taskId") Long taskId) {
return success(importGraphService.findTaskById(taskId));
}
*//**
* 执行导入
*//*
@PostMapping(value = "/graphtaskexecute")
public ResponseData graphTaskExecute(@RequestBody GraphTaskExecuteQ gtQ) {
importGraphService.graphTaskExecute(gtQ);
return success();
}
*//**
* 导入tag和edge
*//*
@PostMapping(value = "/importschema/{space}")
public ResponseData importModel(@PathVariable("space") String space,
@RequestParam("file") MultipartFile file) {
try {
importSchemaService.analysisExcel(space,file.getInputStream());
} catch (IOException e) {
}
return success();
}*/
}

View File

@@ -0,0 +1,242 @@
package com.wx.application.nebula.graph.conrtroller;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.nebula.graph.base.Generators;
import com.wx.application.nebula.graph.bean.ModelEdgeLine;
import com.wx.application.nebula.graph.bean.ModelVertex;
import com.wx.application.nebula.graph.bean.NebulaEdgeLine;
import com.wx.application.nebula.graph.enums.DataType;
import com.wx.application.nebula.graph.query.NebulaQo;
import com.wx.application.nebula.graph.service.ImportModelService;
import com.wx.application.nebula.graph.service.NebulaModelService;
/**
* 本体
* @author zj
*
*/
@RestController
@RequestMapping("/nebula_model")
public class NebulaModelController extends BaseController {
@Autowired
NebulaModelService nebulaModelService;
@Autowired
ImportModelService importModelService;
/**
* 插入模型点
* @param vertex
*/
@PostMapping(value = "/insertmodelvertex")
public ResponseData insertModelVertex(@RequestBody ModelVertex mx) {
if(StringUtils.isBlank(mx.getVid())) {
String vid = Generators.vid(mx.getLabel());
vid = Generators.ontologyVid(mx.getOntologyId(), vid);
mx.setVid(vid);
}
return success(nebulaModelService.insertModelVertex(mx));
}
/**
* 删除一个本体模型点
*/
@GetMapping(value = "/deletemodelvertex/{vid}")
public ResponseData deleteModelVertex(@PathVariable("vid") String vid) {
nebulaModelService.deleteModelVertex(vid);
return success();
}
/**
* 创建一个模型关系
*/
@PostMapping(value = "/insertmodeledge")
public ResponseData insertModelEdge(@RequestBody ModelEdgeLine edge) {
return success(nebulaModelService.insertModelEdge(edge));
}
/**
* 删除一个模型关系
*/
@PostMapping(value = "/deletemodeledge")
public ResponseData deleteModelEdge(@RequestBody NebulaEdgeLine edge) {
nebulaModelService.deleteModelEdge(edge);
return success();
}
/**
* 根据OntologyId删除所有的本体和关系
*/
@GetMapping(value = "/deleteallbyontologyid/{ontologyId}")
public ResponseData deleteAllByOntologyId(@PathVariable("ontologyId") Long ontologyId) {
nebulaModelService.deleteAllByOntologyId(ontologyId);
return success();
}
/**
* 根据OntologyId查询的本体和关系用于图谱展示
*/
@PostMapping(value = "/findrelationbyontologyid/{ontologyId}")
public ResponseData findRelationByOntologyId(@PathVariable("ontologyId") Long ontologyId,
@RequestBody NebulaQo nQ) {
return success(nebulaModelService.findRelationByOntologyId(ontologyId, nQ));
}
/**
* 根据OntologyId查询的本体和关系,查询所有的,目前标注用
*/
@PostMapping(value = "/findallgraphbyontologyid/{ontologyId}")
public ResponseData findAllGraphByOntologyId(@PathVariable("ontologyId") Long ontologyId) {
return success(nebulaModelService.findAllGraphByOntologyId(ontologyId));
}
/**
* 复制图模型
*/
@GetMapping(value = "/copybyontologyid/{srcOntologyId}/{dictOntologyId}")
public ResponseData copyByOntologyId(@PathVariable("srcOntologyId")Long srcOntologyId,
@PathVariable("dictOntologyId")Long dictOntologyId) {
nebulaModelService.copyByOntologyId(srcOntologyId, dictOntologyId);
return success();
}
/**
* 根据本体模型创建图空间
*/
@GetMapping(value = "/initgraphdatabase/{ontologyId}/{space}")
public ResponseData initGraphDatabase(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("space") String space) {
nebulaModelService.initGraphDatabase(ontologyId, space);
return success();
}
/**
* 根据模板excel导入模型
* @throws IOException
*/
@PostMapping(value = "/importmodel/{ontologyId}")
public ResponseData importModel(@PathVariable("ontologyId") Long ontologyId,
@RequestParam("file") MultipartFile file) throws IOException {
return success(importModelService.analysisExcel(ontologyId,file.getInputStream()));
}
/**
* 本体空间统计点
*/
@GetMapping(value = "/countvertexsbyontologyid/{ontologyId}")
public ResponseData countVertexsbyontologyid(@PathVariable("ontologyId") Long ontologyId) {
return success(nebulaModelService.countVertexsByOntologyid(ontologyId));
}
/**
* 本体空间统计边
*/
@GetMapping(value = "/countedgesbyontologyid/{ontologyId}")
public ResponseData countEdgesByOntologyid(@PathVariable("ontologyId") Long ontologyId) {
return success(nebulaModelService.countEdgesByOntologyid(ontologyId));
}
/**
* 根据关键统计开始节点和 结束节点的数量
*/
@GetMapping(value = "/groupcountvexbyedgebyontologyid/{ontologyId}")
public ResponseData groupCountVexByEdgeByOntologyid(@PathVariable("ontologyId") Long ontologyId) {
return success(nebulaModelService.groupCountVexByEdgeByOntologyid(ontologyId));
}
/**
* 图空间的值属性数量分组聚合
*/
@GetMapping(value = "/groupfieldbyontologyid/{ontologyId}")
public ResponseData groupFieldByOntologyId(@PathVariable("ontologyId") Long ontologyId) {
return success(nebulaModelService.groupFieldByOntologyId(ontologyId));
}
/**
* 模型空间根据概念id查找path
*/
@GetMapping(value = "/findpathbyid/{ontologyId}/{vid}")
public ResponseData findPathById(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("vid") String vid) {
return success(nebulaModelService.findPathById(ontologyId, vid));
}
/**
* 模型空间根据id查找节点
*/
@GetMapping(value = "/findnodebyid/{ontologyId}/{vid}")
public ResponseData findNodeById(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("vid") String vid) {
return success(nebulaModelService.findNodeById(vid));
}
/**
* 通过对象属性名称查询所有的path
*/
@GetMapping(value = "/findpathbyedgelabel/{ontologyId}/{label}")
public ResponseData findPathByEdgeLabel(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("label") String label) {
return success(nebulaModelService.findPathByEdgeLabel(ontologyId,label));
}
/**
* 通过值属性名称查询所有概念
*/
@GetMapping(value = "/findnodesbyfield/{ontologyId}/{field}")
public ResponseData findNodesbyField(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("field") String field) {
return success(nebulaModelService.findNodesbyField(ontologyId, field));
}
/**
* 获得值域列表
*/
@GetMapping(value = "/getdatatype")
public ResponseData getDataType() {
return success(DataType.values());
}
/**
* 模型空间根据概念id对象属性列表
*/
@GetMapping(value = "/findlistpathbyid/{ontologyId}/{vid}")
public ResponseData findListPathById(@PathVariable("ontologyId") Long ontologyId,
@PathVariable("vid") String vid) {
return success(nebulaModelService.findListPathById(vid));
}
/**
* 递归
* 查询当前节点的值属性,包含继承的值属性
*/
@GetMapping(value = "/findnebulafieldwithparents/{vid}")
public ResponseData findNebulaFieldWithParents(@PathVariable("vid") String vid) {
return success(nebulaModelService.findNebulaFieldWithParents(vid));
}
}

View File

@@ -0,0 +1,438 @@
package com.wx.application.nebula.graph.conrtroller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wx.application.base.BaseController;
import com.wx.application.base.ResponseData;
import com.wx.application.nebula.graph.bean.NebulaEdge;
import com.wx.application.nebula.graph.bean.NebulaEdgeLine;
import com.wx.application.nebula.graph.bean.NebulaIndex;
import com.wx.application.nebula.graph.bean.NebulaSpace;
import com.wx.application.nebula.graph.bean.NebulaTag;
import com.wx.application.nebula.graph.bean.NebulaVertex;
import com.wx.application.nebula.graph.query.NebulaQo;
import com.wx.application.nebula.graph.service.NebulaOperateService;
@SuppressWarnings("rawtypes")
@RestController
@RequestMapping("/nebula_operate")
public class NebulaOperateController extends BaseController {
@Autowired
NebulaOperateService nebulaOperateService;
/**
* 查看所有的图空间
*/
@GetMapping(value = "/showspace")
public ResponseData showSpace() {
return success(nebulaOperateService.findSpace());
}
/**
* 空间创建语句
* @param space
* @return
*/
@PostMapping(value = "/createspace")
public ResponseData createSpace(@RequestBody NebulaSpace space) {
nebulaOperateService.createSpace(space);
return success(space);
}
/**
* 删除莫个图空间
* @param e
* @return
*/
@GetMapping(value = "/dropspace/{space}")
public ResponseData dropSpace(@PathVariable("space") String space) {
nebulaOperateService.dropSpace(space);
return success();
}
/**
* 显示莫个图空间的详细信息
* @param e
* @return
*/
@GetMapping(value = "/descspace/{space}")
public ResponseData descSpace(@PathVariable("space") String space) {
return success(nebulaOperateService.descSpace(space));
}
/**
* 标签创建语句
* @param space
* @return
*/
@PostMapping(value = "/createtag/{space}")
public ResponseData createTag(@PathVariable("space") String space, @RequestBody NebulaTag e) {
nebulaOperateService.createTag(space, e);
return success();
}
/**
* 标签添加字段语句
* @param space
* @return
*/
@PostMapping(value = "/alteraddtag/{space}")
public ResponseData alterAddTag(@PathVariable("space") String space, @RequestBody NebulaTag e) {
nebulaOperateService.alterAddTag(space, e);
return success();
}
/**
* 标签删除字段语句
* @param space
* @return
*/
@PostMapping(value = "/alterdroptag/{space}")
public ResponseData alterDropTag(@PathVariable("space") String space, @RequestBody NebulaTag e) {
nebulaOperateService.alterDropTag(space, e);
return success();
}
/**
* 标签修改字段语句
* @param space
* @return
*/
@PostMapping(value = "/alterchangetag/{space}")
public ResponseData alterChangeTag(@PathVariable("space") String space, @RequestBody NebulaTag e) {
nebulaOperateService.alterChangeTag(space, e);
return success();
}
/**
* 标签删除
* @param e
* @return
*/
@GetMapping(value = "/droptag/{space}/{tag}")
public ResponseData dropTag(@PathVariable("space") String space, @PathVariable("tag") String tag) {
nebulaOperateService.dropTag(space, tag);
return success();
}
/**
* 查看所有标签
* @param e
* @return
*/
@GetMapping(value = "/showtag/{space}")
public ResponseData showTag(@PathVariable("space") String space) {
return success(nebulaOperateService.showTag(space,true));
}
/**
* 查看标签的创建语句
* @param e
* @return
*/
@GetMapping(value = "/showcreatetag/{space}/{tag}")
public ResponseData showCreateTag(@PathVariable("space") String space,
@PathVariable("tag") String tag) {
return success(nebulaOperateService.showCreateTag(space, tag));
}
/**
* 标签查看详细信息
* @param e
* @return
*/
@GetMapping(value = "/desctag/{space}/{tag}")
public ResponseData descTag(@PathVariable("space") String space, @PathVariable("tag") String tag) {
return success(nebulaOperateService.descTag(space, tag));
}
/**
* 边创建语句
* @param space
* @return
*/
@PostMapping(value = "/createedge/{space}")
public ResponseData createEdge(@PathVariable("space") String space, @RequestBody NebulaEdge e) {
nebulaOperateService.createEdge(space, e);
return success();
}
/**
* 边添加字段语句
* @param space
* @return
*/
@PostMapping(value = "/alteraddedge/{space}")
public ResponseData alterAddEdge(@PathVariable("space") String space, @RequestBody NebulaEdge e) {
nebulaOperateService.alterAddEdge(space, e);
return success();
}
/**
* 边删除字段语句
* @param space
* @return
*/
@PostMapping(value = "/alterdropedge/{space}")
public ResponseData alterDropEdge(@PathVariable("space") String space, @RequestBody NebulaEdge e) {
nebulaOperateService.alterDropEdge(space, e);
return success();
}
/**
* 边修改字段语句
* @param space
* @return
*/
@PostMapping(value = "/alterchangeedge/{space}")
public ResponseData alterChangeEdge(@PathVariable("space") String space, @RequestBody NebulaEdge e) {
nebulaOperateService.alterChangeEdge(space, e);
return success();
}
/**
* 边删除
* @param e
* @return
*/
@GetMapping(value = "/dropedge/{space}/{edge}")
public ResponseData dropEdge(@PathVariable("space") String space, @PathVariable("edge") String edge) {
nebulaOperateService.dropEdge(space, edge);
return success();
}
/**
* 查看标签的创建语句
* @param e
* @return
*/
@GetMapping(value = "/showcreateedge/{space}/{edge}")
public ResponseData showCreateEdge(@PathVariable("space") String space,
@PathVariable("edge") String edge) {
return success(nebulaOperateService.showCreateEdge(space, edge));
}
/**
* 查看所有边
* @param e
* @return
*/
@GetMapping(value = "/showedge/{space}")
public ResponseData showEdge(@PathVariable("space") String space) {
return success(nebulaOperateService.showEdge(space,true));
}
/**
* 边查看详细信息
* @param e
* @return
*/
@GetMapping(value = "/descedge/{space}/{edge}")
public ResponseData descEdge(@PathVariable("space") String space, @PathVariable("edge") String edge) {
return success(nebulaOperateService.descEdge(space, edge));
}
/**
* 索引创建语句
* @param e
* @return
*/
@PostMapping(value = "/createindex/{space}")
public ResponseData createIndex(@PathVariable("space") String space, @RequestBody NebulaIndex e) {
nebulaOperateService.createIndex(space, e);
return success();
}
/**
* 查看边或者标签的索引
* @param e
* @return
*/
@GetMapping(value = "/showindex/{space}/{type}")
public ResponseData showIndex(@PathVariable("space") String space, @PathVariable("type") String type) {
return success(nebulaOperateService.showIndex(space, type));
}
/**
* 删除边或者标签的索引
* @param e
* @return
*/
@PostMapping(value = "/dropindex/{space}")
public ResponseData dropIndex(@PathVariable("space") String space, @RequestBody NebulaIndex e) {
nebulaOperateService.dropIndex(space, e);
return success();
}
/**
* 删除点语句
*/
@GetMapping(value = "/deletevertex/{space}/{vid}")
public ResponseData deleteVertex(@PathVariable("space") String space, @PathVariable("vid") String vid) {
nebulaOperateService.deleteVertex(space, vid);
return success();
}
/**
* 添加点语句
*/
@PostMapping(value = "/insertvertex/{space}/{tag}")
public ResponseData insertVertex(@PathVariable("space") String space
,@PathVariable("tag") String tag, @RequestBody NebulaVertex e) {
nebulaOperateService.insertVertex(space, tag, e);
return success(e);
}
/**
* 边数据删除语句
* @param space
* @return
*/
@PostMapping(value = "/deleteedgeline/{space}/{edge}")
public ResponseData deleteEdgeData(@PathVariable("space") String space,
@PathVariable("edge") String edge, @RequestBody NebulaEdgeLine e) {
nebulaOperateService.deleteEdgeLine(space, edge, e);
return success();
}
/**
* 插入边数据
* @param e
* @return
*/
@PostMapping(value = "/insertedgeline/{space}/{edge}")
public ResponseData insertEdgeData(@PathVariable("space") String space,
@PathVariable("edge") String edge, @RequestBody NebulaEdgeLine e) {
nebulaOperateService.insertEdgeLine(space,edge, e);
return success();
}
/**
* 根据id查找一个节点不用使用tag的
*/
@GetMapping(value = "/findnodebyid/{space}/{vid}")
public ResponseData findNodeById(@PathVariable("space") String space,
@PathVariable("vid") String vid) {
return success(nebulaOperateService.findNodeById(space, vid));
}
/**
* 根据id查找一个节点需要使用tag的
*/
@GetMapping(value = "/findnodebyid/{space}/{tag}/{vid}")
public ResponseData findNodeById(@PathVariable("space") String space,
@PathVariable("tag") String tag,@PathVariable("vid") String vid) {
return success(nebulaOperateService.findNodeById(space, tag, vid));
}
/**
* 根据查询条件查询tag下面的一个节点
*/
@PostMapping(value = "/findnodebykeyword/{space}/{tag}")
public ResponseData findNodeByKeyword(@PathVariable("space") String space,
@PathVariable("tag") String tag,
@RequestBody NebulaQo nQo) {
return success(nebulaOperateService.findNodeByKeyword(space, tag, nQo));
}
/**
* 根据2个节点id获取一条边
*/
@GetMapping(value = "/findrelationbyid/{space}/{edge}/{srcVid}/{dstVid}")
public ResponseData findRelationById(@PathVariable("space") String space,
@PathVariable("edge") String edge
,@PathVariable("srcVid") String srcVid
,@PathVariable("dstVid") String dstVid) {
return success(nebulaOperateService.findRelationById(space, edge, srcVid, dstVid));
}
/**
* 查询一个节点的周边一层节点关系
* @param nQ
* @return
*/
@GetMapping(value = "/findonepathbyid/{space}/{vid}")
public ResponseData findOnePathById(@PathVariable("space") String space,
@PathVariable("vid") String vid) {
return success(nebulaOperateService.findOnePathById(space, vid));
}
/**
* 查询一个头节点和尾结点的关系
* @param nQ
* @return
*/
@GetMapping(value = "/findonepathbysrcidanddctid/{space}/{srcId}/{dctId}")
public ResponseData findOnePathBySrcIdAndDctId(@PathVariable("space") String space,
@PathVariable("srcId") String srcId, @PathVariable("dctId") String dctId) {
return success(nebulaOperateService.findOnePathBySrcIdAndDctId(space, srcId, dctId));
}
/**
* 根据图空间查询图谱
* 已知tag edge 查询(可没有)
*/
@PostMapping(value = "/findpathinspace/{space}")
public ResponseData findPathInSpace(@PathVariable("space") String space,
@RequestBody NebulaQo nebulaQo) {
return success(nebulaOperateService.findPathInSpace(space, nebulaQo));
}
/**
* 根据图空间查询图谱
* 已知tag 查询
*/
@PostMapping(value = "/findnodes/{space}")
public ResponseData findNodes(@PathVariable("space") String space,
@RequestBody NebulaQo nebulaQo) {
return success(nebulaOperateService.findNodes(space, nebulaQo));
}
/**
* 根据图空间查询图谱
* 已知edge 查询
*/
@PostMapping(value = "/findrelations/{space}")
public ResponseData findrelations(@PathVariable("space") String space,
@RequestBody NebulaQo nebulaQo) {
return success(nebulaOperateService.findRelations(space, nebulaQo));
}
/**
* 根据图空间进行统计
* @param space
* @return
*/
@GetMapping(value = "/censusgraphbyspace/{space}")
public ResponseData censusgraphbyspace(@PathVariable("space") String space) {
return success(nebulaOperateService.censusGraphBySpace(space));
}
}

View File

@@ -0,0 +1,16 @@
package com.wx.application.nebula.graph.enums;
public enum DataType {
INT64,
INT32,
INT16,
INT8,
FLOAT,
DOUBLE,
BOOL,
STRING,
DATE,
TIME,
DATETIME,
FIXED_STRING
}

View File

@@ -0,0 +1,6 @@
package com.wx.application.nebula.graph.enums;
public enum IndexType {
TAG,
EDGE
}

View File

@@ -0,0 +1,7 @@
package com.wx.application.nebula.graph.enums;
public enum VidType {
FIXED_STRING;
}

View File

@@ -0,0 +1,69 @@
package com.wx.application.nebula.graph.factory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NebulaGraphClient {
private GenericObjectPool<Session> clientPool;
public NebulaGraphClient(SessionFactory sessionFactory) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
//最大连接
poolConfig.setMaxTotal(100);
//最大空闲连接
poolConfig.setMaxIdle(5);
//最小空闲连接
poolConfig.setMinIdle(5);
poolConfig.setTestWhileIdle(true);
poolConfig.setTestOnCreate(true);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
//连接满时最多等待时间
/*poolConfig.setMaxWaitMillis(5000L);
//使用时检查对象(默认不检查)
poolConfig.setTestWhileIdle(true);
poolConfig.setTestOnCreate(true);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
//jmx启用 之后可以实时的查看线程池对象的状态
poolConfig.setJmxEnabled(false);
poolConfig.setJmxNameBase("namebase");
poolConfig.setJmxNamePrefix("nameprefix");
//驱逐线程每次检查对象个数
poolConfig.setNumTestsPerEvictionRun(2);
//空闲连接被驱逐前能够保留的时间
poolConfig.setMinEvictableIdleTimeMillis(10000L);
//当空闲线程大于minIdle 空闲连接能够保留时间,同时指定会被上面的覆盖
poolConfig.setSoftMinEvictableIdleTimeMillis(10000L);
//驱逐线程执行间隔时间
poolConfig.setTimeBetweenEvictionRunsMillis(200000L);
//放弃长时间占用连接的对象
AbandonedConfig abandonedConfig=new AbandonedConfig();
abandonedConfig.setLogAbandoned(true);
abandonedConfig.setUseUsageTracking(false);
abandonedConfig.setRemoveAbandonedOnBorrow(true);
abandonedConfig.setRemoveAbandonedOnMaintenance(true);
abandonedConfig.setRemoveAbandonedTimeout(20);//second*/
this.clientPool = new GenericObjectPool<>(sessionFactory, poolConfig);
}
public Session getSession() throws Exception {
return clientPool.borrowObject();
}
public void returnSession(Session session) {
if(session == null) {
return;
}
clientPool.returnObject(session);
}
}

View File

@@ -0,0 +1,37 @@
package com.wx.application.nebula.graph.factory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
@Component
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "nebula.session")
public class NebulaSessionProperties {
/**
* ftp地址
*/
private String host;
/**
* 端口号
*/
private Integer port = 9669;
/**
* 登录用户
*/
private String username;
/**
* 登录密码
*/
private String password;
}

View File

@@ -0,0 +1,35 @@
package com.wx.application.nebula.graph.factory;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*/
@Configuration
@EnableConfigurationProperties(NebulaSessionProperties.class)
public class SessionConfigure {
private NebulaSessionProperties nebulaSessionProperties;
@Autowired
public void setFtpClientProperties(NebulaSessionProperties nebulaSessionProperties) {
this.nebulaSessionProperties = nebulaSessionProperties;
}
@Bean
public SessionFactory getSessionFactory() {
return new SessionFactory(nebulaSessionProperties);
}
@Bean
@PostConstruct
public NebulaGraphClient nebulaGraphClient() {
NebulaGraphClient nebulaGraphClient = new NebulaGraphClient(getSessionFactory());
return nebulaGraphClient;
}
}

View File

@@ -0,0 +1,98 @@
package com.wx.application.nebula.graph.factory;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import com.vesoft.nebula.client.graph.NebulaPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.extern.slf4j.Slf4j;
/**
* Session工厂类通过Session工厂提供Session实例的创建和销毁
*/
@Slf4j
public class SessionFactory extends BasePooledObjectFactory<Session> {
NebulaPool pool;
NebulaSessionProperties properties;
public SessionFactory(NebulaSessionProperties properties) {
NebulaPool pool = new NebulaPool();
NebulaPoolConfig nebulaPoolConfig = new NebulaPoolConfig();
nebulaPoolConfig.setMaxConnSize(100);
List<HostAddress> addresses = Arrays.asList(
new HostAddress(properties.getHost(), properties.getPort()));
try {
pool.init(addresses, nebulaPoolConfig);
} catch (Exception e) {
log.info("{}", e);
}
this.properties = properties;
this.pool = pool;
}
/**
* 创建对象
*/
@Override
public Session create() {
Session session = null;
try {
session = pool.getSession(properties.getUsername(), properties.getPassword(), false);
} catch (Exception e) {
log.info("{}",e);
}
return session;
}
/**
* 用PooledObject封装对象放入池中
*/
@Override
public PooledObject<Session> wrap(Session session) {
return new DefaultPooledObject<>(session);
}
/**
* 销毁对象
*/
@Override
public void destroyObject(PooledObject<Session> sessionPooled) {
if (sessionPooled == null) {
return;
}
try {
Session session = sessionPooled.getObject();
session.release();
} catch (Exception e) {
log.error("failed to release session: {}", e);
}
}
/**
* 验证对象
*/
@Override
public boolean validateObject(PooledObject<Session> sessionPooled) {
if (sessionPooled == null) {
return false;
}
try {
Session session = sessionPooled.getObject();
return session.ping();
} catch (Exception e) {
log.error("failed to validate session: {}", e);
}
return false;
}
}

View File

@@ -0,0 +1,22 @@
package com.wx.application.nebula.graph.query;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaModel {
/**
* 构建返回节点
*/
private List<NebulaNode> nodes;
/**
* 构建返回的关系
*/
private List<NebulaRelation> relations;
}

View File

@@ -0,0 +1,45 @@
package com.wx.application.nebula.graph.query;
import java.util.Map;
import com.vesoft.nebula.client.graph.data.ValueWrapper;
import com.wx.application.nebula.graph.base.ResultSetUtils;
import cn.hutool.json.JSONObject;
import lombok.Data;
@Data
public class NebulaNode {
private String vid;
private String labels;
private JSONObject properties;
public void setProperties(JSONObject obj) {
this.properties = obj;
}
public void setProperties(Map<String, ValueWrapper> propertiesMap) {
JSONObject obj = new JSONObject();
for (Map.Entry<String, ValueWrapper> pro : propertiesMap.entrySet()) {
obj.set(pro.getKey(), ResultSetUtils.printValueWrapper(pro.getValue()));
}
this.properties = obj;
}
@Override
public boolean equals(Object obj) {
NebulaNode u = (NebulaNode) obj;
return this.getVid().equals(u.getVid());
}
@Override
public int hashCode() {
String in = this.getVid();
return in.hashCode();
}
}

View File

@@ -0,0 +1,16 @@
package com.wx.application.nebula.graph.query;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
public class NebulaPath {
private NebulaNode srcnode;
private NebulaNode dctnode;
private NebulaRelation relation;
}

View File

@@ -0,0 +1,22 @@
package com.wx.application.nebula.graph.query;
import lombok.Data;
@Data
public class NebulaQo {
private String tag;
private String edge;
private String field = "name";
private String keyword;
private Boolean pageFlag = true;
private Integer page = 1;
private Integer pageSize = 200;
}

View File

@@ -0,0 +1,48 @@
package com.wx.application.nebula.graph.query;
import java.util.Map;
import cn.hutool.json.JSONObject;
import com.vesoft.nebula.client.graph.data.ValueWrapper;
import com.wx.application.nebula.graph.base.ResultSetUtils;
import lombok.Data;
@SuppressWarnings("rawtypes")
@Data
public class NebulaRelation {
private String srcId;
private String dstId;
private String edgeName;
private JSONObject properties;
public void setProperties(JSONObject obj) {
this.properties = obj;
}
public void setProperties(Map<String, ValueWrapper> propertiesMap) {
JSONObject obj = new JSONObject();
for (Map.Entry<String, ValueWrapper> pro : propertiesMap.entrySet()) {
obj.set(pro.getKey(), ResultSetUtils.printValueWrapper(pro.getValue()));
}
this.properties = obj;
}
@Override
public boolean equals(Object obj) {
NebulaRelation u = (NebulaRelation) obj;
return this.getSrcId().equals(u.getSrcId())
&& this.getDstId().equals(u.getDstId());
}
@Override
public int hashCode() {
String in = this.getSrcId().concat(this.getDstId());
return in.hashCode();
}
}

View File

@@ -0,0 +1,62 @@
package com.wx.application.nebula.graph.query;
import java.util.List;
import lombok.Data;
@Data
public class Page {
private List<?> records;
private Integer total;
private Integer page;
private Integer pageSize;
public Page() {
}
public Page(List<?> records, Integer total, Integer page, Integer pageSize) {
this.records = records;
this.total = total;
this.page = page;
this.pageSize = pageSize;
}
public List<?> getRecords() {
return records;
}
public void setRecords(List<?> records) {
this.records = records;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
}

View File

@@ -0,0 +1,22 @@
package com.wx.application.nebula.graph.query;
import lombok.Data;
@Data
public class PageRequest {
private Integer page = 1;
private Integer pageSize = 200;
public static PageRequest of(Integer page,Integer pageSize) {
PageRequest pt = new PageRequest();
pt.setPage(page);
pt.setPageSize(pageSize);
return pt;
}
public Integer skip() {
return (page-1 < 0?0:page-1) * pageSize;
}
}

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