first commit

This commit is contained in:
cherry 2024-05-15 15:52:13 +08:00
commit 11485c6cbe
160 changed files with 11710 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
!**/src/main/resources/temp/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar

13
deploy/bin/shutdown.bat Normal file
View File

@ -0,0 +1,13 @@
@echo off
if not exist "%JAVA_HOME%\bin\jps.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1
setlocal
set "PATH=%JAVA_HOME%\bin;%PATH%"
echo killing per-ftp
for /f "tokens=1" %%i in ('jps -m ^| find "per-ftp"') do ( taskkill /F /PID %%i )
echo Done!

16
deploy/bin/shutdown.sh Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
cd `dirname $0`/../target
target_dir=`pwd`
pid=`ps ax | grep -i 'per-ftp' | grep ${target_dir} | grep java | grep -v grep | awk '{print $1}'`
if [ -z "$pid" ] ; then
echo "No per-ftp running.."
exit 0;
fi
echo "The per-ftp(${pid}) is running..."
kill ${pid}
echo "Send shutdown request to per-ftp(${pid}) OK"

30
deploy/bin/startup.bat Normal file
View File

@ -0,0 +1,30 @@
@echo off
if not exist "%JAVA_HOME%\bin\java.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1
set "JAVA=%JAVA_HOME%\bin\java.exe"
setlocal enabledelayedexpansion
set BASE_DIR=%~dp0
rem added double quotation marks to avoid the issue caused by the folder names containing spaces.
rem removed the last 5 chars(which means \bin\) to get the base DIR.
set BASE_DIR="%BASE_DIR:~0,-5%"
set DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
set CUSTOM_SEARCH_LOCATIONS=%DEFAULT_SEARCH_LOCATIONS%,file:%BASE_DIR%/conf/
set SERVER=per-ftp
set "JAVA_OPT=%JAVA_OPT% -Xms1024m -Xmx1024m -Xmn512m"
set "JAVA_OPT=%JAVA_OPT% -Dsystem.basedir=%BASE_DIR%"
set "JAVA_OPT=%JAVA_OPT% -Dloader.path=%BASE_DIR%/plugins/health -jar %BASE_DIR%\target\%SERVER%.jar"
set "JAVA_OPT=%JAVA_OPT% --spring.config.location=%CUSTOM_SEARCH_LOCATIONS%"
set "JAVA_OPT=%JAVA_OPT% --logging.config=%BASE_DIR%/conf/log4j2.xml"
call "%JAVA%" %JAVA_OPT% per-ftp %*
pause

52
deploy/bin/startup.sh Normal file
View File

@ -0,0 +1,52 @@
#!/bin/sh
error_exit ()
{
echo "ERROR: $1 !!"
exit 1
}
[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=$HOME/jdk/java
[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=/usr/java
[ ! -e "$JAVA_HOME/bin/java" ] && unset JAVA_HOME
if [ -z "$JAVA_HOME" ]; then
error_exit "Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better!"
fi
export SERVER="knowledgebase"
export JAVA_HOME
export JAVA="$JAVA_HOME/bin/java"
export BASE_DIR=`cd $(dirname $0)/..; pwd`
export DEFAULT_SEARCH_LOCATIONS="classpath:/,classpath:/config/,file:./,file:./config/"
export CUSTOM_SEARCH_LOCATIONS=${DEFAULT_SEARCH_LOCATIONS},file:${BASE_DIR}/conf/
#===========================================================================================
# JVM Configuration
#===========================================================================================
JAVA_OPT="${JAVA_OPT} -Xms512m -Xmx512m -Xmn512m"
#JAVA_OPT="${JAVA_OPT} -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
JAVA_OPT="${JAVA_OPT} -Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${JAVA_HOME}/lib/ext:${BASE_DIR}/plugins/cmdb:${BASE_DIR}/plugins/mysql"
JAVA_OPT="${JAVA_OPT} -Dsystem.basedir=${BASE_DIR}"
JAVA_OPT="${JAVA_OPT} -Dloader.path=${BASE_DIR}/plugins/health -jar ${BASE_DIR}/target/${SERVER}.jar"
JAVA_OPT="${JAVA_OPT} ${JAVA_OPT_EXT}"
#JAVA_OPT="${JAVA_OPT} --spring.config.location=${CUSTOM_SEARCH_LOCATIONS}"
JAVA_OPT="${JAVA_OPT} --logging.config=${BASE_DIR}/conf/log4j2.xml"
JAVA_OPT="${JAVA_OPT} --server.max-http-header-size=524288"
if [ ! -d "${BASE_DIR}/logs" ]; then
mkdir ${BASE_DIR}/logs
fi
echo "$JAVA ${JAVA_OPT}"
echo "knowledgeis starting ..."
nohup $JAVA ${JAVA_OPT} per-ftp >> /dev/null 2>&1 &
echo "knowledge is startingyou can check the ${BASE_DIR}/logs/default.log"

551
doc/db/01-kb.sql Normal file
View File

@ -0,0 +1,551 @@
-- ----------------------------
-- Table structure for kb_attachment
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_attachment";
CREATE TABLE "public"."kb_attachment"
(
"attachment_name" varchar COLLATE "pg_catalog"."default",
"attachment_path" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"id" int8
)
;
COMMENT
ON COLUMN "public"."kb_attachment"."attachment_name" IS '附件名';
COMMENT
ON COLUMN "public"."kb_attachment"."attachment_path" IS '附件路径 不到host 例如 /20240301/uthjkksjhlgl.jpg?xxx';
COMMENT
ON COLUMN "public"."kb_attachment"."create_by_id" IS '上传附件的人id';
COMMENT
ON TABLE "public"."kb_attachment" IS '附件表';
-- ----------------------------
-- Table structure for kb_base
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_base";
CREATE TABLE "public"."kb_base"
(
"id" int8 NOT NULL,
"base_name" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"create_by_name" varchar COLLATE "pg_catalog"."default",
"dept_id" varchar COLLATE "pg_catalog"."default",
"is_public" int4,
"update_by_id" varchar COLLATE "pg_catalog"."default",
"update_by_name" varchar COLLATE "pg_catalog"."default",
"update_time" int4,
"category_count" int8,
"knowledge_count" int8,
"dept_name" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_base"."base_name" IS '库名';
COMMENT
ON COLUMN "public"."kb_base"."dept_id" IS '部门id';
COMMENT
ON COLUMN "public"."kb_base"."is_public" IS '是否公开 0 非公开 1 公开';
COMMENT
ON TABLE "public"."kb_base" IS '';
-- ----------------------------
-- Table structure for kb_browse_history
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_browse_history";
CREATE TABLE "public"."kb_browse_history"
(
"id" int8 NOT NULL,
"user_id" varchar COLLATE "pg_catalog"."default",
"knowledge_id" int8,
"create_time" int4
)
;
COMMENT
ON TABLE "public"."kb_browse_history" IS '浏览历史';
-- ----------------------------
-- Table structure for kb_category
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_category";
CREATE TABLE "public"."kb_category"
(
"id" int8 NOT NULL,
"pid" int8,
"category_name" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"update_time" int4,
"update_by_id" varchar COLLATE "pg_catalog"."default",
"kb_count" int4,
"base_id" int8,
"category_full_name" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_category"."pid" IS '父级id';
COMMENT
ON COLUMN "public"."kb_category"."category_name" IS '分类名字';
COMMENT
ON COLUMN "public"."kb_category"."create_time" IS '创建时间';
COMMENT
ON COLUMN "public"."kb_category"."create_by_id" IS '创建id';
COMMENT
ON COLUMN "public"."kb_category"."update_time" IS '更新时间';
COMMENT
ON COLUMN "public"."kb_category"."update_by_id" IS '更新id';
COMMENT
ON COLUMN "public"."kb_category"."kb_count" IS '知识数量';
COMMENT
ON COLUMN "public"."kb_category"."base_id" IS '库id';
COMMENT
ON COLUMN "public"."kb_category"."category_full_name" IS '分类串';
COMMENT
ON TABLE "public"."kb_category" IS '分类表';
-- ----------------------------
-- Table structure for kb_ik
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_ik";
CREATE TABLE "public"."kb_ik"
(
"id" int8 NOT NULL,
"user_id" varchar COLLATE "pg_catalog"."default",
"user_name" varchar COLLATE "pg_catalog"."default",
"word" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"browse_history_id" int8
)
;
COMMENT
ON COLUMN "public"."kb_ik"."user_name" IS '用户名';
COMMENT
ON COLUMN "public"."kb_ik"."word" IS '分词结果';
COMMENT
ON COLUMN "public"."kb_ik"."browse_history_id" IS '搜索历史的id';
COMMENT
ON TABLE "public"."kb_ik" IS '搜索的分词表, 便于以后做智能推荐';
-- ----------------------------
-- Table structure for kb_knowledge
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge";
CREATE TABLE "public"."kb_knowledge"
(
"id" int8 NOT NULL,
"title" varchar(255) COLLATE "pg_catalog"."default",
"description" varchar(255) COLLATE "pg_catalog"."default",
"category_id" int8,
"create_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"create_by_name" varchar(255) COLLATE "pg_catalog"."default",
"update_time" int4,
"update_by_id" varchar COLLATE "pg_catalog"."default",
"update_by_name" varchar COLLATE "pg_catalog"."default",
"is_text" int4 DEFAULT 0,
"is_image" int4 DEFAULT 0,
"is_doc" int4 DEFAULT 0,
"is_video" int4 DEFAULT 0,
"is_publish" int4 DEFAULT 0,
"collection_num" int4 DEFAULT 0,
"view_num" int4 DEFAULT 0,
"base_id" int8,
"attachment_type" varchar COLLATE "pg_catalog"."default",
"resource" varchar COLLATE "pg_catalog"."default",
"publish_time" int4,
"implement_time" int4,
"comment_num" int8,
"is_public" int4,
"attachment_path" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_knowledge"."title" IS '标题';
COMMENT
ON COLUMN "public"."kb_knowledge"."description" IS '摘要';
COMMENT
ON COLUMN "public"."kb_knowledge"."category_id" IS '分类id';
COMMENT
ON COLUMN "public"."kb_knowledge"."create_time" IS '创建时间';
COMMENT
ON COLUMN "public"."kb_knowledge"."create_by_id" IS '创建者id';
COMMENT
ON COLUMN "public"."kb_knowledge"."create_by_name" IS '创建者姓名';
COMMENT
ON COLUMN "public"."kb_knowledge"."update_time" IS '更新时间';
COMMENT
ON COLUMN "public"."kb_knowledge"."update_by_id" IS '更新者id';
COMMENT
ON COLUMN "public"."kb_knowledge"."update_by_name" IS '更新者姓名';
COMMENT
ON COLUMN "public"."kb_knowledge"."is_text" IS '是否是文本类型 0 否 1 是';
COMMENT
ON COLUMN "public"."kb_knowledge"."is_image" IS '是否是图片类型 0 否 1 是';
COMMENT
ON COLUMN "public"."kb_knowledge"."is_doc" IS '是否是文档类型 0 否 1 是';
COMMENT
ON COLUMN "public"."kb_knowledge"."is_video" IS '是否是视频类型 0 否 1 是';
COMMENT
ON COLUMN "public"."kb_knowledge"."is_publish" IS '是否发布 0 未发布 1 已发布';
COMMENT
ON COLUMN "public"."kb_knowledge"."collection_num" IS '收藏量';
COMMENT
ON COLUMN "public"."kb_knowledge"."view_num" IS '浏览量';
COMMENT
ON COLUMN "public"."kb_knowledge"."attachment_type" IS '附件类型 pdf doc docx 等';
COMMENT
ON COLUMN "public"."kb_knowledge"."publish_time" IS '发布时间';
COMMENT
ON COLUMN "public"."kb_knowledge"."implement_time" IS '实施时间';
COMMENT
ON COLUMN "public"."kb_knowledge"."attachment_path" IS '附件路径';
-- ----------------------------
-- Table structure for kb_knowledge_attachment
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_attachment";
CREATE TABLE "public"."kb_knowledge_attachment"
(
"knowledge_id" int8,
"attachment_id" int8,
"id" bigserial
)
;
-- ----------------------------
-- Table structure for kb_knowledge_category
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_category";
CREATE TABLE "public"."kb_knowledge_category"
(
"id" int8,
"knowledge_id" int8,
"category_id" int8 NOT NULL
)
;
COMMENT
ON TABLE "public"."kb_knowledge_category" IS '知识的分类';
-- ----------------------------
-- Table structure for kb_knowledge_collection
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_collection";
CREATE TABLE "public"."kb_knowledge_collection"
(
"id" int8 NOT NULL,
"knowlegde_id" int8,
"user_id" varchar COLLATE "pg_catalog"."default",
"create_time" int4
)
;
COMMENT
ON TABLE "public"."kb_knowledge_collection" IS '个人收藏表';
-- ----------------------------
-- Table structure for kb_knowledge_comment
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_comment";
CREATE TABLE "public"."kb_knowledge_comment"
(
"id" int8 NOT NULL,
"comment" varchar COLLATE "pg_catalog"."default",
"knowledge_id" int8,
"create_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"create_by_name" varchar COLLATE "pg_catalog"."default",
"update_time" int4,
"update_by_id" varchar COLLATE "pg_catalog"."default",
"update_by_name" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_knowledge_comment"."comment" IS '评论内容';
COMMENT
ON COLUMN "public"."kb_knowledge_comment"."knowledge_id" IS '知识id';
COMMENT
ON COLUMN "public"."kb_knowledge_comment"."create_time" IS '创建时间';
COMMENT
ON COLUMN "public"."kb_knowledge_comment"."create_by_id" IS '创建者id';
COMMENT
ON COLUMN "public"."kb_knowledge_comment"."create_by_name" IS '创建者姓名';
COMMENT
ON TABLE "public"."kb_knowledge_comment" IS '知识评论';
-- ----------------------------
-- Table structure for kb_knowledge_content
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_content";
CREATE TABLE "public"."kb_knowledge_content"
(
"knowledge_id" int8,
"knowledge_content" text COLLATE "pg_catalog"."default",
"id" bigserial
)
;
COMMENT
ON COLUMN "public"."kb_knowledge_content"."knowledge_id" IS '知识id';
COMMENT
ON COLUMN "public"."kb_knowledge_content"."knowledge_content" IS '知识内容';
COMMENT
ON TABLE "public"."kb_knowledge_content" IS '知识内容';
-- ----------------------------
-- Table structure for kb_knowledge_img
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_img";
CREATE TABLE "public"."kb_knowledge_img"
(
"knowledge_id" int8,
"img_path" varchar COLLATE "pg_catalog"."default",
"id" bigserial
)
;
COMMENT
ON TABLE "public"."kb_knowledge_img" IS '知识附件上传上来的pdf转的图片';
-- ----------------------------
-- Table structure for kb_knowledge_resource
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_resource";
CREATE TABLE "public"."kb_knowledge_resource"
(
"knowledge_id" int8,
"resource_id" int8,
"id" bigserial
)
;
COMMENT
ON COLUMN "public"."kb_knowledge_resource"."knowledge_id" IS '知识id';
COMMENT
ON COLUMN "public"."kb_knowledge_resource"."resource_id" IS '来源id';
COMMENT
ON TABLE "public"."kb_knowledge_resource" IS '知识来源表';
-- ----------------------------
-- Table structure for kb_knowledge_tag
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_knowledge_tag";
CREATE TABLE "public"."kb_knowledge_tag"
(
"knowledge_id" int8,
"tag_id" int8,
"id" bigserial
)
;
COMMENT
ON COLUMN "public"."kb_knowledge_tag"."knowledge_id" IS '知识id';
COMMENT
ON COLUMN "public"."kb_knowledge_tag"."tag_id" IS '标签id';
COMMENT
ON TABLE "public"."kb_knowledge_tag" IS '知识的标签表';
-- ----------------------------
-- Table structure for kb_menu
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_menu";
CREATE TABLE "public"."kb_menu"
(
"id" int8 NOT NULL,
"menu_name" varchar COLLATE "pg_catalog"."default",
"menu_path" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_menu"."menu_name" IS '菜单名';
COMMENT
ON COLUMN "public"."kb_menu"."menu_path" IS '菜单路径';
COMMENT
ON TABLE "public"."kb_menu" IS '通过user_id查询菜单 前端展示这些菜单实现权限控制';
-- ----------------------------
-- Table structure for kb_resource
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_resource";
CREATE TABLE "public"."kb_resource"
(
"id" int8 NOT NULL,
"resource_name" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"update_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"update_by_id" varchar COLLATE "pg_catalog"."default",
"create_by_name" varchar COLLATE "pg_catalog"."default",
"update_by_name" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_resource"."resource_name" IS '来源名';
COMMENT
ON COLUMN "public"."kb_resource"."create_time" IS '创建时间';
COMMENT
ON COLUMN "public"."kb_resource"."update_time" IS '更新时间';
COMMENT
ON COLUMN "public"."kb_resource"."create_by_id" IS '创建者id';
COMMENT
ON COLUMN "public"."kb_resource"."update_by_id" IS '更新者id';
COMMENT
ON COLUMN "public"."kb_resource"."create_by_name" IS '创建者姓名';
COMMENT
ON COLUMN "public"."kb_resource"."update_by_name" IS '更新者姓名';
COMMENT
ON TABLE "public"."kb_resource" IS '来源表';
-- ----------------------------
-- Table structure for kb_search_history
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_search_history";
CREATE TABLE "public"."kb_search_history"
(
"id" int8 NOT NULL,
"user_id" varchar COLLATE "pg_catalog"."default",
"user_name" varchar COLLATE "pg_catalog"."default",
"search_word" varchar COLLATE "pg_catalog"."default",
"create_time" int4
)
;
COMMENT
ON COLUMN "public"."kb_search_history"."user_id" IS '用户id';
COMMENT
ON COLUMN "public"."kb_search_history"."user_name" IS '用户姓名';
COMMENT
ON COLUMN "public"."kb_search_history"."search_word" IS '搜索词';
COMMENT
ON COLUMN "public"."kb_search_history"."create_time" IS '创建时间';
COMMENT
ON TABLE "public"."kb_search_history" IS '搜索历史';
-- ----------------------------
-- Table structure for kb_tag
-- ----------------------------
DROP TABLE IF EXISTS "public"."kb_tag";
CREATE TABLE "public"."kb_tag"
(
"id" int8 NOT NULL,
"tag_name" varchar COLLATE "pg_catalog"."default",
"create_time" int4,
"update_time" int4,
"create_by_id" varchar COLLATE "pg_catalog"."default",
"update_by_id" varchar COLLATE "pg_catalog"."default",
"create_by_name" varchar COLLATE "pg_catalog"."default",
"update_by_name" varchar COLLATE "pg_catalog"."default"
)
;
COMMENT
ON COLUMN "public"."kb_tag"."tag_name" IS '标签名';
COMMENT
ON COLUMN "public"."kb_tag"."create_time" IS '创建时间';
COMMENT
ON COLUMN "public"."kb_tag"."update_time" IS '更新时间';
COMMENT
ON COLUMN "public"."kb_tag"."create_by_id" IS '创建者id';
COMMENT
ON COLUMN "public"."kb_tag"."update_by_id" IS '更新者id';
COMMENT
ON COLUMN "public"."kb_tag"."create_by_name" IS '创建者姓名';
COMMENT
ON COLUMN "public"."kb_tag"."update_by_name" IS '更新者姓名';
COMMENT
ON TABLE "public"."kb_tag" IS '标签表';
-- ----------------------------
-- Primary Key structure for table kb_base
-- ----------------------------
ALTER TABLE "public"."kb_base"
ADD CONSTRAINT "kb_base_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_browse_history
-- ----------------------------
ALTER TABLE "public"."kb_browse_history"
ADD CONSTRAINT "kb_browse_history_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_category
-- ----------------------------
ALTER TABLE "public"."kb_category"
ADD CONSTRAINT "kb_category_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_ik
-- ----------------------------
ALTER TABLE "public"."kb_ik"
ADD CONSTRAINT "kb_ik_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge
-- ----------------------------
ALTER TABLE "public"."kb_knowledge"
ADD CONSTRAINT "kb_knowledge_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_attachment
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_attachment"
ADD CONSTRAINT "kb_knowledge_attachment_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_category
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_category"
ADD CONSTRAINT "kb_knowledge_category_pkey" PRIMARY KEY ("category_id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_collection
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_collection"
ADD CONSTRAINT "kb_collection_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_comment
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_comment"
ADD CONSTRAINT "kb_comment_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_content
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_content"
ADD CONSTRAINT "kb_knowlegde_content_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_img
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_img"
ADD CONSTRAINT "kb_knowledge_img_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_resource
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_resource"
ADD CONSTRAINT "kb_knowledge_resource_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_knowledge_tag
-- ----------------------------
ALTER TABLE "public"."kb_knowledge_tag"
ADD CONSTRAINT "kb_knowlegde_tag_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_menu
-- ----------------------------
ALTER TABLE "public"."kb_menu"
ADD CONSTRAINT "kb_menu_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_resource
-- ----------------------------
ALTER TABLE "public"."kb_resource"
ADD CONSTRAINT "kb_resource_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_search_history
-- ----------------------------
ALTER TABLE "public"."kb_search_history"
ADD CONSTRAINT "kb_search_history_pkey" PRIMARY KEY ("id");
-- ----------------------------
-- Primary Key structure for table kb_tag
-- ----------------------------
ALTER TABLE "public"."kb_tag"
ADD CONSTRAINT "kb_tag_pkey" PRIMARY KEY ("id");

59
doc/es/1.0.index Normal file
View File

@ -0,0 +1,59 @@
公共库 mapping
PUT knowledge-public
{"mappings": {
"dynamic": "false",
"properties": {
"id": {
"type": "long"
},
"title": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
},
"content": {
"type": "text",
"analyzer": "ik_smart",
"search_analyzer": "ik_smart"
},
"createTime": {
"type": "long"
},
"createById": {
"type": "keyword"
},
"createByName": {
"type": "keyword"
},
"updateTime": {
"type": "long"
},
"updateById": {
"type": "keyword"
},
"updateByName": {
"type": "keyword"
},
"categoryId": {
"type": "long"
},
"baseId": {
"type": "long"
},
"deptId":{
"type":"keyword"
},
"resourcesList": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}}},
"collectionUsers": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}}}}}}

308
mvnw vendored Normal file
View File

@ -0,0 +1,308 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.2.0
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /usr/local/etc/mavenrc ] ; then
. /usr/local/etc/mavenrc
fi
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"; export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] &&
JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then
if $darwin ; then
javaHome="$(dirname "\"$javaExecutable\"")"
javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac"
else
javaExecutable="$(readlink -f "\"$javaExecutable\"")"
fi
javaHome="$(dirname "\"$javaExecutable\"")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(cd "$wdir/.." || exit 1; pwd)
fi
# end of workaround
done
printf '%s' "$(cd "$basedir" || exit 1; pwd)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' < "$1"
fi
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget > /dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
while IFS="=" read -r key value; do
case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;;
esac
done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum > /dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then
wrapperSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available."
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties."
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
exit 1
fi
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

205
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,205 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.2.0
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%

266
pom.xml Normal file
View File

@ -0,0 +1,266 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.kb</groupId>
<artifactId>knowledgeBase</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>knowledgeBase</name>
<description>knowledgeBase</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<!--Druid数据源依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.18</version>
</dependency>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.0.3</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<!-- PDFBox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>lib</directory>
<targetPath>/BOOT-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,47 @@
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>bin</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>true</includeBaseDirectory>
<files>
<file>
<fileMode>775</fileMode>
<source>target/${project.build.finalName}.jar</source>
<destName>knowledgebase.jar</destName>
<outputDirectory>./target</outputDirectory>
</file>
</files>
<fileSets>
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory>./conf</outputDirectory>
<includes>
<include>application.yml</include>
</includes>
</fileSet>
<fileSet>
<directory>src/main/resources/logconf</directory>
<outputDirectory>./conf</outputDirectory>
<includes>
<include>log4j2.xml</include>
</includes>
</fileSet>
<fileSet>
<fileMode>775</fileMode>
<directory>deploy/bin</directory>
<outputDirectory>./bin</outputDirectory>
</fileSet>
<fileSet>
<directory>deploy/db</directory>
<outputDirectory>./db</outputDirectory>
</fileSet>
</fileSets>
</assembly>

View File

@ -0,0 +1,18 @@
package com.kb.knowledgebase;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.kb.knowledgebase.modules.**.mapper")
@Slf4j
public class KnowledgeBaseApplication {
public static void main(String[] args) {
SpringApplication.run(KnowledgeBaseApplication.class, args);
log.info("====================================启动完成====================================");
}
}

View File

@ -0,0 +1,51 @@
package com.kb.knowledgebase.authority;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(tags = {"授权"})
@RestController
@RequestMapping("/knowledgeSystem")
public class AuthorityController extends BaseController {
@Autowired
private AuthorityServiceImpl authorityServiceImpl;
@ApiOperation("获取授权信息(Token)")
@GetMapping("/getAuthority")
public ResponseResult<AuthorityToken> getAuthority(@RequestParam("auth_code") String authCode) {
return result(authorityServiceImpl.getToken(authCode));
}
@ApiOperation("刷新令牌")
@GetMapping("/refreshToken")
public ResponseResult<AuthorityToken> refreshToken(@RequestParam("token") String token) {
return result(authorityServiceImpl.refreshToken(token));
}
@ApiOperation("获取个人信息")
@GetMapping("/getUserInfo")
public ResponseResult<UserInfo> getUserInfo(@RequestParam("token") String token) {
return result(authorityServiceImpl.getUserInfoFromThreadLocalUtil(token));
}
@ApiOperation("登出(注销令牌)")
@GetMapping("/logout")
public ResponseResult logout(@RequestParam("token") String token) {
authorityServiceImpl.logout(token);
return result();
}
@ApiOperation("登出回调接口")
@PostMapping("/logoutCallback")
public ResponseResult logoutCallback(@RequestBody AuthorityToken token) {
authorityServiceImpl.deleteLocalToken(token.getToken());
return result();
}
}

View File

@ -0,0 +1,317 @@
package com.kb.knowledgebase.authority;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.knowledgebase.entity.MyException;
import com.kb.knowledgebase.entity.ReturnCode;
import com.kb.knowledgebase.entity.knowledge.Attachment;
import com.kb.knowledgebase.modules.knowledge.mapper.AttachmentMapper;
import com.kb.knowledgebase.modules.util.CommonDateUtil;
import com.kb.knowledgebase.modules.util.SignUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@Service
@Slf4j
public class AuthorityServiceImpl implements IAuthorityService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${app.baseUrl}")
private String appBaseUrl;
@Value("${app.key}")
private String appKey;
@Value("${app.secret}")
private String appSecret;
/**
* 获取令牌
*
* @param authCode 授权码
* @return token
*/
@Override
public AuthorityToken getToken(String authCode) {
log.info("获取令牌: " + authCode);
OkHttpClient client = new OkHttpClient();
// 定义签名参数
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("authCode", authCode);
// 时间戳
final Long systemTimeMillis = CommonDateUtil.getSystemTimeMillis();
String systemTime = systemTimeMillis.toString();
Request request = new Request.Builder()
.url(doCreateUrl("/dgpc/sso/getToken", paramMap))
.method("GET", null)
.addHeader("appKey", appKey)
.addHeader("timestamp", systemTime)
.addHeader("sign", SignUtil.getSign(appKey, appSecret, paramMap, systemTime))
.build();
try {
try (Response response = client.newCall(request).execute()) {
if (response.body() != null) {
final JSON responseJSON = doGetResponseJSON(response);
final JSON dataJSON = (JSON) responseJSON.getByPath("data");
// 访问令牌
String token = String.valueOf(dataJSON.getByPath("token"));
// 刷新令牌
String refreshToken = String.valueOf(dataJSON.getByPath("refreshToken"));
// 访问令牌的有效期
Long expiresIn = Long.parseLong(String.valueOf(dataJSON.getByPath("expires")));
AuthorityToken authorityToken = new AuthorityToken();
authorityToken.setToken(token);
authorityToken.setRefreshToken(refreshToken);
authorityToken.setExpiresIn(expiresIn);
final UserInfo userInfo = getUserInfo(token);
authorityToken.setUserInfo(userInfo);
stringRedisTemplate.opsForValue().set(token, JSONUtil.toJsonStr(authorityToken), expiresIn - 500, TimeUnit.SECONDS);
return authorityToken;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
/**
* 刷新令牌
*
* @param token 旧令牌
* @return token
*/
@Override
public AuthorityToken refreshToken(String token) {
log.info("刷新令牌: " + token);
final AuthorityToken authorityToken = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(token), AuthorityToken.class);
if (StringUtil.isNullOrEmpty(authorityToken.getRefreshToken())) {
throw new MyException(ReturnCode.AUTH_ERROR);
}
return doRefreshToken(authorityToken.getRefreshToken());
}
private AuthorityToken doRefreshToken(String refreshToken) {
// 定义签名参数
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("refreshToken", refreshToken);
// 时间戳
final Long systemTimeMillis = CommonDateUtil.getSystemTimeMillis();
String systemTime = systemTimeMillis.toString();
Request request = new Request.Builder()
.url(doCreateUrl("/dgpc/sso/refreshToken", paramMap))
.method("GET", null)
.addHeader("appKey", appKey)
.addHeader("timestamp", systemTime)
.addHeader("sign", SignUtil.getSign(appKey, appSecret, paramMap, systemTime))
.build();
OkHttpClient client = new OkHttpClient();
try {
try (Response response = client.newCall(request).execute()) {
if (response.body() != null) {
final JSON responseJSON = doGetResponseJSON(response);
final JSON dataJSON = (JSON) responseJSON.getByPath("data");
// 访问令牌
String newToken = String.valueOf(dataJSON.getByPath("token"));
// 刷新令牌
String newRefreshToken = String.valueOf(dataJSON.getByPath("refreshToken"));
// 访问令牌的有效期
Long expiresIn = Long.parseLong(String.valueOf(dataJSON.getByPath("expires")));
// 返回值
AuthorityToken authorityTokenResult = new AuthorityToken();
authorityTokenResult.setToken(newToken);
authorityTokenResult.setRefreshToken(newRefreshToken);
authorityTokenResult.setExpiresIn(expiresIn);
final UserInfo userInfo = getUserInfo(authorityTokenResult.getToken());
authorityTokenResult.setUserInfo(userInfo);
// 存redis
stringRedisTemplate.opsForValue().set(newToken, JSONUtil.toJsonStr(authorityTokenResult), expiresIn - 500, TimeUnit.SECONDS);
return authorityTokenResult;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
private static JSON doGetResponseJSON(Response response) throws IOException {
assert response.body() != null;
final String str = response.body().string();
return JSONUtil.parse(str);
}
/**
* 获取用户信息
*
* @param token 令牌
* @return 用户信息
*/
@Override
public UserInfo getUserInfo(String token) {
log.info("获取用户信息: " + token);
OkHttpClient client = new OkHttpClient();
String url = "/dgpc/sso/info";
// 定义签名参数
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("token", token);
// 时间戳
String systemTime = CommonDateUtil.getSystemTimeMillis().toString();
// 定义请求参数
RequestBody requestBody = RequestBody.create(JSONUtil.toJsonStr(paramMap),
MediaType.parse(APPLICATION_JSON_VALUE));
// 发请求
Request request = new Request.Builder()
.url(doGetFullUrl(url))
.post(requestBody)
.addHeader("appKey", appKey)
.addHeader("timestamp", systemTime)
.addHeader("sign", SignUtil.getSign(appKey, appSecret, paramMap, systemTime))
.build();
try {
try (Response response = client.newCall(request).execute()) {
if (response.body() != null) {
final JSON responseJSON = doGetResponseJSON(response);
final JSONObject dataJSON = (JSONObject) responseJSON.getByPath("data");
final UserInfo userInfo = JSONUtil.toBean(dataJSON, UserInfo.class);
if (null != userInfo.getDeptIds() && userInfo.getDeptIds().length > 0) {
userInfo.setDeptIds(Arrays.stream(userInfo.getDeptIds())
.filter(StringUtils::hasText)
.toArray(String[]::new)
);
}
return userInfo;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
/**
* 注销令牌
*
* @param token 令牌
*/
@Override
public void logout(String token) {
log.info("注销令牌: " + token);
OkHttpClient client = new OkHttpClient();
String url = "/dgpc/sso/logout";
// 定义签名参数
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("token", token);
// 时间戳
String systemTime = CommonDateUtil.getSystemTimeMillis().toString();
// 定义请求参数
RequestBody requestBody = new FormBody.Builder()
.add("token", token)
.build();
// 发请求
Request request = new Request.Builder()
.url(doGetFullUrl(url))
.post(requestBody)
.addHeader("appKey", appKey)
.addHeader("timestamp", systemTime)
.addHeader("sign", SignUtil.getSign(appKey, appSecret, paramMap, systemTime))
.build();
try (Response response = client.newCall(request).execute()) {
if (response.body() != null) {
final String res = response.body().string();
log.info("logout res: " + res);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 获取用户信息(从ThreadLocalUtil)
*
* @param token 令牌
* @return 用户信息
*/
@Override
public UserInfo getUserInfoFromThreadLocalUtil(String token) {
return ThreadLocalUtil.getUserInfo();
}
/**
* 回调登出本地令牌销毁
*
* @param token 令牌
* @return 用户信息
*/
@Override
public void deleteLocalToken(String token) {
log.info("回调登出(本地令牌销毁)" + token);
stringRedisTemplate.delete(token);
}
private HttpUrl doCreateUrl(String url, Map<String, String> paramMap) {
final HttpUrl httpUrl = HttpUrl.parse(doGetFullUrl(url));
assert httpUrl != null;
HttpUrl.Builder urlBuilder = httpUrl.newBuilder();
if (!CollectionUtils.isEmpty(paramMap)) {
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
}
}
return urlBuilder.build();
}
private String doGetFullUrl(String url) {
return appBaseUrl + url;
}
}

View File

@ -0,0 +1,32 @@
package com.kb.knowledgebase.authority;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="AuthorityToken对象", description="令牌对象")
public class AuthorityToken extends BaseEntity implements Serializable {
@ApiModelProperty(value = "访问令牌")
private String token;
@ApiModelProperty(value = "刷新令牌")
private String refreshToken;
@ApiModelProperty(value = "过期秒数")
private Long expiresIn;
@ApiModelProperty(value = "用户信息")
private UserInfo userInfo;
}

View File

@ -0,0 +1,54 @@
package com.kb.knowledgebase.authority;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IAuthorityService {
/**
* 获取令牌
*
* @param authCode 授权码
* @return token
*/
AuthorityToken getToken(String authCode);
/**
* 刷新令牌
*
* @param token 旧令牌
* @return token
*/
AuthorityToken refreshToken(String token);
/**
* 获取用户信息
*
* @param token 令牌
* @return 用户信息
*/
UserInfo getUserInfo(String token);
/**
* 注销令牌
*
* @param token 令牌
*/
void logout(String token);
/**
* 获取用户信息(从ThreadLocalUtil)
*
* @param token 令牌
* @return 用户信息
*/
UserInfo getUserInfoFromThreadLocalUtil(String token);
/**
* 回调登出本地令牌销毁
*
* @param token 令牌
* @return 用户信息
*/
void deleteLocalToken(String token);
}

View File

@ -0,0 +1,82 @@
package com.kb.knowledgebase.authority;
import cn.hutool.json.JSONUtil;
import com.kb.knowledgebase.config.KbProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class MyInterceptor implements HandlerInterceptor {
private static final String HEADER_BEARER_PREFIX = "Bearer ";
@Autowired
private IAuthorityService authorityServiceImpl;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private KbProperties kbProperties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
UserInfo userInfo = doGetUserInfo(request);
if (null == userInfo) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
ThreadLocalUtil.setUserInfo(userInfo);
return true;
}
private UserInfo doGetUserInfo(HttpServletRequest request) {
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
if (!StringUtils.hasText(token)) {
if (Boolean.TRUE.equals(kbProperties.getMockUserEnabled())) {
UserInfo userInfo = new UserInfo();
userInfo.setId("U123123123");
userInfo.setUsername("test01");
userInfo.setDeptId("D01");
userInfo.setDeptName("部门1");
return userInfo;
}
return null;
}
final int idx = token.indexOf(HEADER_BEARER_PREFIX);
if (idx >= 0) {
token = token.substring(idx + HEADER_BEARER_PREFIX.length());
}
final String tkStr = stringRedisTemplate.opsForValue().get(token);
if (!StringUtils.hasText(tkStr)) {
log.warn("无效的令牌, 空");
return null;
}
try {
final AuthorityToken authorityToken = JSONUtil.toBean(tkStr, AuthorityToken.class);
return authorityToken.getUserInfo();
} catch (Exception e) {
log.info("token invalid", e);
}
return null;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ThreadLocalUtil.clearUserInfo(); // 清除用户信息避免内存泄漏
}
}

View File

@ -0,0 +1,18 @@
package com.kb.knowledgebase.authority;
public class ThreadLocalUtil {
private static final ThreadLocal<UserInfo> userInfoThreadLocal = new ThreadLocal<>();
public static UserInfo getUserInfo() {
return userInfoThreadLocal.get();
}
public static void setUserInfo(UserInfo userInfo) {
userInfoThreadLocal.set(userInfo);
}
public static void clearUserInfo() {
userInfoThreadLocal.remove();
}
}

View File

@ -0,0 +1,56 @@
package com.kb.knowledgebase.authority;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="UserInfo对象", description="用户信息对象")
public class UserInfo extends BaseEntity implements Serializable {
@ApiModelProperty(value="用户ID")
private String id;
@ApiModelProperty(value="用户姓名")
private String username;
@ApiModelProperty(value="租户ID")
private String tenantId;
@ApiModelProperty(value="租户名称")
private String tenantName;
@ApiModelProperty(value="机构ID")
private String deptId;
@ApiModelProperty(value="机构名称")
private String deptName;
@ApiModelProperty(value="机构ID集合一个用户多个机构场景")
private String[] deptIds;
@ApiModelProperty(value="登录账号")
private String account;
@ApiModelProperty(value="手机号")
private String phone;
@ApiModelProperty(value="邮箱")
private String email;
@ApiModelProperty(value="是否启用01")
private Boolean enabled;
@ApiModelProperty(value="角色ID集合")
private String[] roleIdSet;
}

View File

@ -0,0 +1,65 @@
package com.kb.knowledgebase.config;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
@Configuration
public class ElasticSearchClientConfig {
@Value("${elasticsearch.endpoint}")
private String endpoint;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.scheme}")
private String scheme;
@Value("${elasticsearch.username:}")
private String username;
@Value("${elasticsearch.password:}")
private String password;
@Bean
public ElasticsearchClient elasticsearchClient(){
//获取可以用来操作ES的java客户端
// RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
// RestClient.builder(new HttpHost("127.0.0.1", 9200,"http")));
// return restHighLevelClient;
HttpHost host = new HttpHost(endpoint, port, scheme);
RestClientBuilder builder = RestClient.builder(host);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
}
RestClient restClient = builder.build();
// 使用Jackson映射器创建传输层
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// 创建API客户端
ElasticsearchClient client = new ElasticsearchClient(transport);
return client;
}
}

View File

@ -0,0 +1,48 @@
package com.kb.knowledgebase.config;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.knowledgebase.entity.MyException;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.util.HashMap;
/**
* 全局异常捕获
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Object handleException(Exception e, HttpServletRequest request) {
log.info("请求错误,请求地址{},错误信息:", request.getRequestURL(), e);
return ResponseResult.error("系统异常","500", new Object[0]);
}
@ExceptionHandler(value = MyException.class)
public Object handleCommonException(MyException ex) {
log.error("通用异常信息", ex);
return ResponseResult.error(ex.getMessage(), new Object[0]);
}
}

View File

@ -0,0 +1,14 @@
package com.kb.knowledgebase.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author quangz
* @version 1.0
*/
@Configuration
@EnableConfigurationProperties(KbProperties.class)
public class KbConfig {
}

View File

@ -0,0 +1,17 @@
package com.kb.knowledgebase.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author quangz
* @version 1.0
*/
@Data
@ConfigurationProperties("kb")
public class KbProperties {
/**
* 是否启用mock用户
*/
private Boolean mockUserEnabled;
}

View File

@ -0,0 +1,33 @@
package com.kb.knowledgebase.config;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Data
@Component
public class MinIoClientConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
/**
* 注入minio 客户端
*
* @return
*/
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}

View File

@ -0,0 +1,18 @@
package com.kb.knowledgebase.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfig {
//分页拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
return interceptor;
}
}

View File

@ -0,0 +1,21 @@
package com.kb.knowledgebase.config;
import com.kb.knowledgebase.authority.AuthorityToken;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, AuthorityToken> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, AuthorityToken> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}

View File

@ -0,0 +1,52 @@
package com.kb.knowledgebase.config;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.kb.knowledgebase.authority.MyInterceptor;
import com.kb.knowledgebase.core.jackson.KbJavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
import java.util.TimeZone;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
private static final String ASIA_SHANGHAI = "Asia/Shanghai";
@Bean
@ConditionalOnMissingBean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ASIA_SHANGHAI));
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.modules(new KbJavaTimeModule());
};
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor)
.addPathPatterns("/attachment/**")
.addPathPatterns("/category/**")
.addPathPatterns("/knowledgeBase/**")
.addPathPatterns("/knowledge/**")
.addPathPatterns("/mine/**")
.addPathPatterns("/statistics/**")
.addPathPatterns("/tag/**")
.addPathPatterns("/resource/**");
}
}

View File

@ -0,0 +1,25 @@
package com.kb.knowledgebase.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class corsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOriginPattern("*"); // 允许谁跨域
configuration.setAllowCredentials(true); // 传cookie
configuration.addAllowedMethod("*"); // 允许哪些方法跨域 post/get
configuration.addAllowedHeader("*"); // 允许哪些头信息
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 拦截一切请求
return new CorsFilter(source);
}
}

View File

@ -0,0 +1,54 @@
package com.kb.knowledgebase.core.jackson;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.PackageVersion;
import com.fasterxml.jackson.datatype.jsr310.deser.*;
import com.fasterxml.jackson.datatype.jsr310.ser.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
/**
* @author quangz
* @version 1.0
*/
public class KbJavaTimeModule extends SimpleModule {
public KbJavaTimeModule() {
super(PackageVersion.VERSION);
// ======================= 时间序列化规则 ===============================
// yyyy-MM-dd HH:mm:ss
this.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
// yyyy-MM-dd
this.addSerializer(LocalDate.class,
new LocalDateSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
// HH:mm:ss
this.addSerializer(LocalTime.class,
new LocalTimeSerializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
// Instant 类型序列化
this.addSerializer(Instant.class, InstantSerializer.INSTANCE);
// Duration 类型序列化
this.addSerializer(Duration.class, DurationSerializer.INSTANCE);
// ======================= 时间反序列化规则 ==============================
// yyyy-MM-dd HH:mm:ss
this.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
// yyyy-MM-dd
this.addDeserializer(LocalDate.class,
new LocalDateDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)));
// HH:mm:ss
this.addDeserializer(LocalTime.class,
new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN)));
// Instant 反序列化
this.addDeserializer(Instant.class, InstantDeserializer.INSTANT);
// Duration 反序列化
this.addDeserializer(Duration.class, DurationDeserializer.INSTANCE);
}
}

View File

@ -0,0 +1,45 @@
package com.kb.knowledgebase.entity;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class MyException extends RuntimeException {
//错误码
private String code;
//错误信息
private String message;
public MyException() {
super();
}
/**
* 自定义300
* @param message
*/
public MyException(String message) {
super(message);
this.code = "300";
this.message = message;
}
public MyException(ReturnCode returnCode) {
super(returnCode.getMsg());
this.code = returnCode.getCode();
this.message = returnCode.getMsg();
}
public MyException(ReturnCode returnCode,String message) {
super(message);
this.code = returnCode.getCode();
this.message = message;
}
}

View File

@ -0,0 +1,19 @@
package com.kb.knowledgebase.entity;
public enum ReturnCode {
CUSTOM_ERROR("300","自定义错误类型"),//自定义错误
AUTH_ERROR("310","授权错误");
private String code;
private String msg;
ReturnCode(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}

View File

@ -0,0 +1,44 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_ATTACHMENT")
@ToString
@ApiModel(value="Attachment对象", description="附件对象")
public class Attachment extends BaseEntity {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="附件名字")
@TableField(value = "ATTACHMENT_NAME")
private String attachmentName;
@ApiModelProperty(value="附件路径")
@TableField(value = "ATTACHMENT_PATH")
private String attachmentPath;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者")
@TableField(value = "CREATE_BY_ID")
private String createById;
}

View File

@ -0,0 +1,76 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_CATEGORY")
@ToString
@ApiModel(value="Category对象", description="分类对象")
public class Category extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="父级id")
@TableField(value = "PID")
private Long pid;
@ApiModelProperty(value="分类名字")
@TableField(value = "CATEGORY_NAME")
private String categoryName;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="知识数量")
@TableField(value = "KB_COUNT")
private int kbCount;
@ApiModelProperty(value="库id")
@TableField(value = "BASE_ID")
private Long baseId;
@ApiModelProperty(value="分类串")
@TableField(value = "CATEGORY_FULL_NAME")
private String categoryFullName;
@ApiModelProperty(value="占比")
@TableField(exist = false)
private String proportion;
@ApiModelProperty(value="子节点")
@TableField(exist = false)
private List<Category> childrenList;
}

View File

@ -0,0 +1,213 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Transient;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE")
@ToString
@ApiModel(value="Knowledge对象", description="知识库对象")
public class Knowledge extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
/**[
* {
* name :"标签"
* id "xx"
* },
* {
* name :"标签2",
* id :"x1x"
* }
*]
*/
@ApiModelProperty(value="标签组")
@TableField(exist = false)
@Transient
private List<Map<String,String>> tags;
@ApiModelProperty(value="来源组")
@TableField(exist = false)
@Transient
private List<Map<String,String>> resources;
@ApiModelProperty(value="es存的来源id列表")
@TableField(exist = false)
@Transient
private List<Long> resourcesList;
/**[
* {
* name :"标签"
* path "xx"
* },
* {
* name :"标签2",
* path :"x1x"
* }
*]
*/
@ApiModelProperty(value="附件组")
@TableField(exist = false)
@Transient
private List<Map<String,String>> attachments;
@ApiModelProperty(value="标题")
@TableField(value = "TITLE")
private String title;
@ApiModelProperty(value="摘要")
@TableField(value = "DESCRIPTION")
private String description;
@ApiModelProperty(value="内容")
@TableField(exist = false)
private String content;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_TEXT")
private Integer isText;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_IMAGE")
private Integer isImage;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_DOC")
private Integer isDoc;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_VIDEO")
private Integer isVideo;
@ApiModelProperty(value="收藏量")
@TableField(value = "COLLECTION_NUM")
private Integer collectionNum;
@ApiModelProperty(value="评论数量")
@TableField(value = "COMMENT_NUM")
private int commentNum;
@ApiModelProperty(value="浏览量")
@TableField(value = "VIEW_NUM")
private Integer viewNum;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="创建者名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="创建者名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
@ApiModelProperty(value="类别ID")
@TableField(value = "CATEGORY_ID")
private Long categoryId;
@ApiModelProperty(value="是否发布")
@TableField(value = "IS_PUBLISH")
private Integer isPublish;
@ApiModelProperty(value="标签串")
@TableField(exist = false)
private String strTags;
@ApiModelProperty(value="分类串")
@TableField(exist = false)
private String strCategoryIds;
@ApiModelProperty(value="库id")
@TableField(value = "BASE_ID")
private Long baseId;
@ApiModelProperty(value="是否公开")
@TableField(value = "IS_PUBLIC")
private Integer isPublic;
@ApiModelProperty(value="来源")
@TableField(value = "resource")
private String resource;
@ApiModelProperty(value="附件 改成一个附件")
@TableField(value = "ATTACHMENT_PATH")
private String attachmentPath;
@ApiModelProperty(value="只有一个附件 根据类型展示图标")
@TableField(value = "ATTACHMENT_TYPE")
private String attachmentType;
@ApiModelProperty(value="发布时间 不是文章发布时间")
@TableField(value = "PUBLISH_TIME")
private Long publishTime;
@ApiModelProperty(value="发实施时间")
@TableField(value = "IMPLEMENT_TIME")
private Long implementTime;
@ApiModelProperty(value="pdf图片路径")
@TableField(exist = false)
private List<String> imgPaths;
@ApiModelProperty(value="库名称")
@TableField(exist = false)
private String baseName;
@ApiModelProperty(value="库名称")
@TableField(exist = false)
private Integer isCollection;
@ApiModelProperty(value="收藏者列表 不加es插进来就报错")
@TableField(exist = false)
private List<String> collectionUsers;
@ApiModelProperty(value="文件名")
@TableField(exist = false)
private String fileName;
@ApiModelProperty(value="deptid")
@TableField(exist = false)
private String deptId;
}

View File

@ -0,0 +1,80 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_BASE")
@ToString
@ApiModel(value="KnowledgeBase对象", description="库对象")
public class KnowledgeBase extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="库名")
@TableField(value = "BASE_NAME")
private String baseName;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="创建者姓名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="更新者姓名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
@ApiModelProperty(value="部门id")
@TableField(value = "DEPT_ID")
private String deptId;
@ApiModelProperty(value="是否公开 0 非公开 2 公开")
@TableField(value = "IS_PUBLIC")
private int isPublic;
@ApiModelProperty(value="类目数量")
@TableField(value = "CATEGORY_COUNT")
private Long categoryCount;
@ApiModelProperty(value="知识数量")
@TableField(value = "KNOWLEDGE_COUNT")
private Long knowledgeCount;
@ApiModelProperty(value="部门名称")
@TableField(value = "DEPT_NAME")
private String deptName;
}

View File

@ -0,0 +1,54 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE_COLLECTION")
@ToString
@ApiModel(value="KnowledgeCollection对象", description="收藏对象")
public class KnowledgeCollection extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="知识ID")
@TableField(value = "KNOWLEGDE_ID")
private Long knowlegdeId;
@ApiModelProperty(value="用户ID")
@TableField(value = "USER_ID")
private String userId;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="知识对象")
@TableField(exist = false)
private Knowledge knowledge;
@ApiModelProperty(value="主题库串")
@TableField(exist = false)
private String baseStr;
@ApiModelProperty(value="总数")
@TableField(exist = false)
private Long total;
}

View File

@ -0,0 +1,70 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE_COMMENT")
@ToString
@ApiModel(value="KnowledgeComment对象", description="知识评论对象")
public class KnowledgeComment extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="评论内容")
@TableField(value = "COMMENT")
private String comment;
@ApiModelProperty(value="知识id")
@TableField(value = "KNOWLEDGE_ID")
private Long knowledgeId;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="创建者姓名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="更新者姓名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
@ApiModelProperty(value="知识标题")
@TableField(exist = false)
private String title;
@ApiModelProperty(value="知识摘要")
@TableField(exist = false)
private String description;
}

View File

@ -0,0 +1,94 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Transient;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="KnowledgeEs对象", description="知识库请求对象")
public class KnowledgeEs implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="标题")
@TableField(value = "TITLE")
private String title;
@ApiModelProperty(value="内容")
@TableField(value = "CONTENT")
private String content;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="创建者名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="创建者名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
@ApiModelProperty(value="类别ID")
@TableField(value = "CATEGORY_ID")
private Long categoryId;
@ApiModelProperty(value="库id")
@TableField(value = "BASE_ID")
private Long baseId;
@ApiModelProperty(value="资源")
@TableField(value = "RESOURCE")
private String resource;
@ApiModelProperty(value="部门id")
@TableField(value = "DEPT_ID")
private String deptId;
@ApiModelProperty(value="附件 改成一个附件")
@TableField(value = "ATTACHMENT_PATH")
private String attachmentPath;
@ApiModelProperty(value="类型")
@TableField(value = "ATTACHMENT_TYPE")
private String attachmentType;
@ApiModelProperty(value="收藏者列表")
@TableField(exist = false)
private List<String> collectionUsers;
@ApiModelProperty(value="es存的来源id列表")
@TableField(exist = false)
@Transient
private List<Long> resourcesList;
}

View File

@ -0,0 +1,37 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE_RESOURCE")
@ToString
@ApiModel(value="KnowlegdeResource对象", description="知识来源对象")
public class KnowledgeResource extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.AUTO)
private Long id;
@ApiModelProperty(value="知识id")
@TableField(value = "KNOWLEDGE_ID")
private Long knowlegdeId;
@ApiModelProperty(value="来源id")
@TableField(value = "RESOURCE_ID")
private Long resourceId;
}

View File

@ -0,0 +1,37 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE_TAG")
@ToString
@ApiModel(value="KnowledgeTag对象", description="知识标签对象")
public class KnowledgeTag extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.AUTO)
private Long id;
@ApiModelProperty(value="知识id")
@TableField(value = "KNOWLEDGE_ID")
private Long knowlegdeId;
@ApiModelProperty(value="标签id")
@TableField(value = "TAG_ID")
private Long tagId;
}

View File

@ -0,0 +1,153 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_KNOWLEDGE")
@ToString
@ApiModel(value="KnowledgeVo对象", description="知识库请求对象")
public class KnowledgeVo extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
/**[
* {
* name :"标签"
* id "xx"
* },
* {
* name :"标签2",
* id :"x1x"
* }
*]
*/
@ApiModelProperty(value="标签组")
@TableField(exist = false)
private List<Map<String,String>> tags;
/**[
* {
* name :"标签"
* path "xx"
* },
* {
* name :"标签2",
* path :"x1x"
* }
*]
*/
@ApiModelProperty(value="附件组")
@TableField(exist = false)
private List<Map<String,String>> attachments;
@ApiModelProperty(value="查询关键词")
@TableField(exist = false)
private String keyword;
@ApiModelProperty(value="标题")
@TableField(value = "TITLE")
private String title;
@ApiModelProperty(value="内容")
@TableField(value = "CONTENT")
private String content;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_TEXT")
private Integer isText;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_IMAGE")
private Integer isImage;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_DOC")
private Integer isDoc;
@ApiModelProperty(value="知识类型")
@TableField(value = "IS_VIDEO")
private Integer isVideo;
@ApiModelProperty(value="收藏量")
@TableField(value = "COLLECTION_NUM")
private Integer collectionNum;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="创建者名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="创建者名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
@ApiModelProperty(value="类别ID")
@TableField(value = "CATEGORY_ID")
private Long categoryId;
@ApiModelProperty(value="来源list")
@TableField(exist = false)
private List<Integer> resources;
@ApiModelProperty(value="类别ID及下级id")
@TableField(exist = false)
private List<Long> categoryIds;
@ApiModelProperty(value="收藏的文章id 给es查询(哭了)")
@TableField(exist = false)
private List<Long> knowledgeIds;
@ApiModelProperty(value="是否发布")
@TableField(value = "IS_PUBLISH")
private Integer isPublish;
@ApiModelProperty(value="库id")
@TableField(value = "BASE_ID")
private Long baseId;
@ApiModelProperty(value="是否公开")
@TableField(value = "IS_PUBLIC")
private Integer isPublic;
@ApiModelProperty(value="资源")
@TableField(value = "RESOURCE")
private String resource;
@ApiModelProperty(value="收藏者id")
@TableField(exist = false)
private String colletionUserId;
}

View File

@ -0,0 +1,59 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_RESOURCE")
@ToString
@ApiModel(value="Resource对象", description="来源对象")
public class Resource extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="来源名")
@TableField(value = "RESOURCE_NAME")
private String resourceName;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="创建者姓名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新者姓名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
}

View File

@ -0,0 +1,48 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_SEARCH_HISTORY")
@ToString
@ApiModel(value="SearchHistory对象", description="查询历史")
public class SearchHistory implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="用户id")
@TableField(value = "USER_ID")
private String userId;
@ApiModelProperty(value="用户姓名")
@TableField(value = "USER_NAME")
private String userName;
@ApiModelProperty(value="查询关键词")
@TableField(value = "SEARCH_WORD")
private String searchWord;
@ApiModelProperty(value="查询时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
}

View File

@ -0,0 +1,28 @@
package com.kb.knowledgebase.entity.knowledge;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="StatisticsCategoryResult", description="分类统计对象")
public class StatisticsCategoryResult extends BaseEntity implements Serializable {
@ApiModelProperty(value="合计")
private Long total;
@ApiModelProperty(value="详细列表")
private List<Category> categoryList;
}

View File

@ -0,0 +1,28 @@
package com.kb.knowledgebase.entity.knowledge;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="StatisticsKnowledgeResult对象", description="知识统计对象")
public class StatisticsKnowledgeResult extends BaseEntity implements Serializable {
@ApiModelProperty(value="合计")
private Long total;
@ApiModelProperty(value="详细列表")
private List<KnowledgeBase> knowledgeBaseList;
}

View File

@ -0,0 +1,23 @@
package com.kb.knowledgebase.entity.knowledge;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@ToString
@ApiModel(value="统计图表对象", description="图表对象")
public class StatisticsResult {
@ApiModelProperty(value="统计数")
private int value;
@ApiModelProperty(value="名称")
private String name;
}

View File

@ -0,0 +1,60 @@
package com.kb.knowledgebase.entity.knowledge;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kb.knowledgebase.modules.common.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@TableName("KB_TAG")
@ToString
@ApiModel(value="Tag对象", description="标签对象")
public class Tag extends BaseEntity implements Serializable {
@ApiModelProperty(value="id")
@TableId(value = "ID" ,type = IdType.ASSIGN_ID)
private Long id;
@ApiModelProperty(value="标签名")
@TableField(value = "TAG_NAME")
private String tagName;
@ApiModelProperty(value="创建时间")
@TableField(value = "CREATE_TIME")
private Long createTime;
@ApiModelProperty(value="创建者id")
@TableField(value = "CREATE_BY_ID")
private String createById;
@ApiModelProperty(value="更新时间")
@TableField(value = "UPDATE_TIME")
private Long updateTime;
@ApiModelProperty(value="更新者id")
@TableField(value = "UPDATE_BY_ID")
private String updateById;
@ApiModelProperty(value="创建者姓名")
@TableField(value = "CREATE_BY_NAME")
private String createByName;
@ApiModelProperty(value="更新者姓名")
@TableField(value = "UPDATE_BY_NAME")
private String updateByName;
}

View File

@ -0,0 +1,47 @@
package com.kb.knowledgebase.modules.common;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kb.knowledgebase.modules.util.CommonPageUtil;
public class BaseController
// extends BaseController
{
protected <E> IPage<E> getIPage(BaseEntity model) {
return CommonPageUtil.getIPage(model);
}
protected <E> ResponseResult<E> result(IPage<E> iPage) {
return new ResponseResult<>(iPage);
}
protected <E> ResponseResult<E> result(E obj) {
return new ResponseResult<>(ResponseResult.STATUS_SUCCESS, "成功", obj);
}
protected <E> ResponseResult<E> result(E obj,Long currentPage,Long pageSize,Long total) {
return new ResponseResult<>(ResponseResult.STATUS_SUCCESS, "成功",obj,currentPage ,pageSize, total);
}
protected ResponseResult<Object> result() {
return new ResponseResult<>(ResponseResult.STATUS_SUCCESS, "成功", new Object[0]);
}
/**
* 自定义异常
* @param msg
* @return
*/
protected ResponseResult<Object> resultError(String msg) {
return new ResponseResult<>(ResponseResult.STATUS_ERROR, msg);
}
protected ResponseResult<Object> resultError(String msg, Object... args) {
return new ResponseResult<>(ResponseResult.STATUS_ERROR, msg, args);
}
protected ResponseResult<Object> resultError() {
return this.resultError("");
}
}

View File

@ -0,0 +1,40 @@
package com.kb.knowledgebase.modules.common;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
@Data
public class BaseEntity {
// @Override
public Integer getCurrentPage() {
return currentPage;
}
// @Override
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
// @Override
public Integer getPageSize() {
return pageSize;
}
// @Override
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
@ApiModelProperty(value = "页码",hidden = true)
@TableField(exist = false)
private Integer currentPage = 1;
@ApiModelProperty(value = "页面条数",hidden = true)
@TableField(exist = false)
private Integer pageSize = 10;
}

View File

@ -0,0 +1,56 @@
package com.kb.knowledgebase.modules.common;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModelProperty;
public class BaseExcelModel {
/** 错误提示信息 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private String errorMsg;
/** 错误行数 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private Integer rowNum;
public Integer getRowNum() {
return rowNum;
}
public void setRowNum(Integer integer) {
this.rowNum = integer;
}
public String getErrorMsg() {
return errorMsg;
}
// ---------------------
// @Override
public Integer getCurrentPage() {
return currentPage;
}
// @Override
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
// @Override
public Integer getPageSize() {
return pageSize;
}
// @Override
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
@ApiModelProperty(value = "页码",hidden = true)
@TableField(exist = false)
private Integer currentPage;
@ApiModelProperty(value = "页面条数",hidden = true)
@TableField(exist = false)
private Integer pageSize;
}

View File

@ -0,0 +1,18 @@
package com.kb.knowledgebase.modules.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public interface CommonParam {
Integer PAGE_SIZE = 10;
Integer CURRENT_PAGE = 1;
String BUCKET_NAME = "knowledge";
String RESOURCE_DIR = "/tmp";
String KEYWORD_RANKING = "kb_keyword_ranking";
}

View File

@ -0,0 +1,95 @@
package com.kb.knowledgebase.modules.common;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class ResponseResult<T> implements Serializable {
private static final long serialVersionUID = -5945988848945139985L;
public static final String STATUS_SUCCESS = "200";
public static final String STATUS_ERROR = "300";
@ApiModelProperty(value = "状态码", example = "500")
private String code;
@ApiModelProperty(value = "状态描述(用户显示,支持多语言)", example = "操作成功")
private String message;
@ApiModelProperty("业务数据")
private T data;
@ApiModelProperty("分页参数")
private PageParam pageParam;
public ResponseResult() {
}
public static <T> ResponseResult<T> error(String msg, Object... args) {
ResponseResult<T> result = new ResponseResult();
result.setCode(STATUS_ERROR);
result.setMessage(msg);
return result;
}
public static <T> ResponseResult<T> error(String msg, String code,Object... args) {
ResponseResult<T> result = new ResponseResult();
result.setCode(code);
result.setMessage(msg);
return result;
}
public ResponseResult(String code, String message, T data) {
this.code = code;
this.message = message;
if (null == data) {
this.data = (T) (new Object());
} else {
this.data = data;
}
}
/**
* @param iPage
*/
public ResponseResult(IPage<T> iPage) {
this("200", "成功", (T) (iPage.getRecords()));
this.pageParam = new PageParam(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getPages());
}
public ResponseResult(String code, String message,T data,Long currentPage,Long pageSize,Long total) {
this.code = code;
this.message = message;
if (null == data) {
this.data = (T) (new Object());
} else {
this.data = data;
}
double ceil = Math.ceil((double)total / (double)pageSize);
this.pageParam = new PageParam(currentPage,pageSize,total,(long)ceil);
}
public ResponseResult(String code, String message) {
this(code, message, null);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class PageParam {
@ApiModelProperty(value = "页码", example = "1")
private long pageNumber;
@ApiModelProperty(value = "页面条数", example = "10")
private long pageSize;
@ApiModelProperty(value = "总数据条数", example = "9999")
private long total;
@ApiModelProperty(value = "总分页数", example = "100")
private long totalPage;
}

View File

@ -0,0 +1,26 @@
package com.kb.knowledgebase.modules.common.log.annotation;
import java.lang.annotation.*;
/**
* 操作日志注解
*
* @author quangz
* @version 1.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
/**
* 描述
* @return {String}
*/
String value() default "";
/**
* 操作类型
* @return {String}
*/
String type() default "";
}

View File

@ -0,0 +1,58 @@
package com.kb.knowledgebase.modules.common.log.aspect;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.common.log.dto.SysLogDTO;
import com.kb.knowledgebase.modules.common.log.event.SysLogEvent;
import com.kb.knowledgebase.modules.common.log.util.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;
/**
* @author quangz
* @version 1.0
*/
@Slf4j
@Aspect
@RequiredArgsConstructor
public class SysLogAspect {
private final ApplicationEventPublisher publisher;
@SneakyThrows
@Around("@annotation(sysLog)")
public Object around(ProceedingJoinPoint point, SysLog sysLog) {
String strClassName = point.getTarget().getClass().getName();
String strMethodName = point.getSignature().getName();
log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);
String value = sysLog.value();
SysLogDTO logDTO = SysLogUtils.createSysLog();
if (null == logDTO) {
return point.proceed();
}
logDTO.setType(sysLog.type());
logDTO.setOperationDesc(value);
// 发送异步日志事件
Long startTime = System.currentTimeMillis();
Object obj = null;
try {
obj = point.proceed();
} catch (Exception e) {
obj = e;
throw e;
} finally {
Long endTime = System.currentTimeMillis();
logDTO.setDuration(String.valueOf(endTime - startTime));
publisher.publishEvent(new SysLogEvent(point.getTarget(), logDTO, obj));
}
return obj;
}
}

View File

@ -0,0 +1,41 @@
package com.kb.knowledgebase.modules.common.log.config;
import com.kb.knowledgebase.modules.common.log.aspect.SysLogAspect;
import com.kb.knowledgebase.modules.common.log.listener.SysLogMqListener;
import com.kb.knowledgebase.modules.common.log.util.SysLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* @author quangz
* @version 1.0
*/
@Slf4j
@EnableAsync
@Configuration
public class LogAutoConfiguration implements ApplicationContextAware {
@Bean
@ConditionalOnProperty(value = "kb.log.mq.enabled", havingValue = "true")
public SysLogMqListener sysLogMqListener() {
log.info("log mq enabled");
return new SysLogMqListener();
}
@Bean
public SysLogAspect sysLogAspect(ApplicationEventPublisher publisher) {
return new SysLogAspect(publisher);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SysLogUtils.setApplicationContext(applicationContext);
}
}

View File

@ -0,0 +1,29 @@
package com.kb.knowledgebase.modules.common.log.constant;
/**
* @author quangz
* @version 1.0
*/
public interface SysLogTypeConstants {
/**
* 新增
*/
String ADD = "add";
/**
* 查询
*/
String QUERY = "query";
/**
* 更新
*/
String UPDATE = "update";
/**
* 删除
*/
String DELETE = "delete";
}

View File

@ -0,0 +1,55 @@
package com.kb.knowledgebase.modules.common.log.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author quangz
* @version 1.0
*/
@Data
public class SysLogDTO {
@ApiModelProperty(value="用户ID")
private String userId;
@ApiModelProperty(value="用户所属机构id")
private String deptId;
@ApiModelProperty(value="用户名称")
private String userName;
@ApiModelProperty(value="机构名称")
private String userDeptName;
@ApiModelProperty(value="应用key")
private String appKey;
@ApiModelProperty(value="应用名称")
private String appName;
@ApiModelProperty(value="租户id")
private String tenantId;
@ApiModelProperty(value="请求时间yyyy-MM-dd HH:mm:ss")
private String requestTime;
@ApiModelProperty(value="请求ip")
private String ip;
@ApiModelProperty(value="操作类型")
private String type;
@ApiModelProperty(value="操作描述")
private String operationDesc;
@ApiModelProperty(value="请求参数")
private String params;
@ApiModelProperty(value="请求结果")
private String result;
@ApiModelProperty(value="操作时长ms")
private String duration;
}

View File

@ -0,0 +1,23 @@
package com.kb.knowledgebase.modules.common.log.event;
import com.kb.knowledgebase.modules.common.log.dto.SysLogDTO;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
/**
* @author quangz
* @version 1.0
*/
@Getter
public class SysLogEvent extends ApplicationEvent {
private final SysLogDTO sysLog;
private final Object result;
public SysLogEvent(Object source, SysLogDTO sysLog, Object result) {
super(source);
this.sysLog = sysLog;
this.result = result;
}
}

View File

@ -0,0 +1,57 @@
package com.kb.knowledgebase.modules.common.log.listener;
import cn.hutool.json.JSONUtil;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.dto.SysLogDTO;
import com.kb.knowledgebase.modules.common.log.event.SysLogEvent;
import com.kb.knowledgebase.modules.util.ResponseResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
/**
* @author quangz
* @version 1.0
*/
@Slf4j
public class SysLogMqListener {
@Value("${kb.log.mq.topic:sys-log}")
private String topic;
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Async
@Order
@EventListener(SysLogEvent.class)
public void saveSysLog(SysLogEvent event) {
log.info("sending log");
SysLogDTO sysLog = event.getSysLog();
Object result = event.getResult();
if (null == result) {
result = ResponseResultUtils.result();
} else if (result instanceof Exception) {
result = ResponseResultUtils.resultError(((Exception) result).getMessage());
}
sysLog.setResult(JSONUtil.toJsonStr(result));
final String msg = JSONUtil.toJsonStr(sysLog);
kafkaTemplate.send(topic, msg);
log.info("log sent");
if (log.isDebugEnabled()) {
log.debug("log sent msg: " + msg);
}
}
}

View File

@ -0,0 +1,81 @@
/*
*
* Copyright (c) 2018-2025, ihospital All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: ihospital
*
*/
package com.kb.knowledgebase.modules.common.log.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.kb.knowledgebase.authority.ThreadLocalUtil;
import com.kb.knowledgebase.authority.UserInfo;
import com.kb.knowledgebase.modules.common.log.dto.SysLogDTO;
import lombok.experimental.UtilityClass;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
/**
* 系统日志工具类
*
* @author L.cm
*/
@UtilityClass
public class SysLogUtils {
private String appKey;
private String appName;
public SysLogDTO createSysLog() {
HttpServletRequest request = ((ServletRequestAttributes) Objects
.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
SysLogDTO sysLog = new SysLogDTO();
final UserInfo userInfo = ThreadLocalUtil.getUserInfo();
if (null == userInfo) {
return null;
}
sysLog.setUserId(userInfo.getId());
sysLog.setDeptId(userInfo.getDeptId());
sysLog.setUserName(userInfo.getUsername());
sysLog.setUserDeptName(userInfo.getDeptName());
sysLog.setTenantId(userInfo.getTenantId());
sysLog.setAppKey(appKey);
sysLog.setAppName(appName);
sysLog.setRequestTime(DateUtil.formatDateTime(new Date()));
sysLog.setIp(ServletUtil.getClientIP(request));
return sysLog;
}
public void setApplicationContext(ApplicationContext applicationContext) {
final Environment environment = applicationContext.getEnvironment();
appKey = environment.getProperty("app.key");
appName = environment.getProperty("app.name", "知识库");
}
}

View File

@ -0,0 +1,602 @@
package com.kb.knowledgebase.modules.elasticsearch.impl;
import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.mapping.DynamicMapping;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.json.JsonData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kb.knowledgebase.authority.ThreadLocalUtil;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeEs;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static cn.hutool.http.HtmlUtil.cleanHtmlTag;
import static cn.hutool.http.HtmlUtil.removeHtmlTag;
/**
* elasticSearch操作类
* 操作knowledge和comment 索引
*
*/
@Service
@Slf4j
public class ElasticSearchServiceImpl {
@Autowired
@Qualifier("elasticsearchClient") // 找名字为elasticsearchClient的bean
private ElasticsearchClient client;
/**
* 默认的索引
*/
String index = "knowledge";
String commentiIdex = "comment";
String highLightPreTags = "<hlc>";
String highLightPostTags = "</hlc>";
String KB_TITLE = "title";
String KB_CONTENT = "content";
String KB_IS_PUBLISH = "isPublish";
String KB_BASE_ID = "baseId";
String KB_CREATE_TIME = "createTime";
String KB_CREATE_BY_ID = "createById";
String KB_CREATE_BY_NAME = "createByName";
String KB_CATEGORY_ID = "categoryId";
String KB_RESOURCE = "resource";
String KB_RESOURCES_LIST = "resourcesList";
String KB_ID = "id";
String KB_UPDATE_TIME = "updateTime";
String KB_UPDATE_BY_ID = "updateById";
String KB_UPDATE_BY_NAME = "updateByName";
String KB_COLLECTION_USERS = "collectionUsers";
String KB_DEPT_ID = "deptId";
String COLLLECTION_BASE = "knowledge-public";
public void createDocument(KnowledgeEs knowledge, String index) {
try {
CreateResponse createResponse = client.create(e->e.index(index).id(knowledge.getId().toString()).document(knowledge));
System.out.println(createResponse.result());
log.info("新增es中文章id为{} index为{}",knowledge.getId(),index);
} catch (IOException e) {
log.error("新增es中文章id为{} index为{}时报错:{}",knowledge.getId(),index,e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 通过id获取
* @param id
*/
public void queryDocumentById(String id,String index){
// 构建查询请求
GetResponse<Knowledge> response = null;
try {
response = client.get(e -> e.index(index).id(id), Knowledge.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(response.source().toString());
}
/**
* 收藏中查询 跨索引查询 需要两个索引
* @param knowledges
* @param knowledgeVo
* @return
*/
public Long selectCollectionDocument(List<Knowledge> knowledges,KnowledgeVo knowledgeVo,String index){
String indexPublic = COLLLECTION_BASE;
/**
* 朵个索引查询数据
*/
List<String> indexList = new ArrayList<String>(){{add(indexPublic);}};
if(StrUtil.isNotBlank(index)) indexList.add(index);
log.info("收藏接口查询搜索引{}",indexList);
try {
Integer finalCurrentPage = knowledgeVo.getCurrentPage();
Integer finalPageSize = knowledgeVo.getPageSize();
//条件查询器
BoolQuery.Builder boolQuery = new BoolQuery.Builder();
if(!StrUtil.isEmpty(knowledgeVo.getKeyword())){
log.info("Keyword不为空 值:{}",knowledgeVo.getKeyword());
boolQuery.must(m->m.multiMatch( mm-> mm
.fields(KB_TITLE,KB_CONTENT)
.query(knowledgeVo.getKeyword())
));
}
//用户id
if(!StrUtil.isEmpty(knowledgeVo.getColletionUserId())){
log.info("ColletionUserId不为空 值:{}",knowledgeVo.getColletionUserId());
boolQuery.must(m -> m
.term(
t -> t
.field(KB_COLLECTION_USERS + ".keyword").value(knowledgeVo.getColletionUserId())
));
}
// List<Long> knowledgeIds = knowledgeVo.getKnowledgeIds();
//文章id范围查询
// if(null != knowledgeIds && knowledgeIds.size()>0){
// log.info("knowledgeIds不为空 值:{}", knowledgeVo.getKnowledgeIds());
// List<FieldValue> collect = knowledgeIds.stream().map(FieldValue::of).collect(Collectors.toList());
// boolQuery.must(
// m -> m
// .terms(
// v -> v
// .field(KB_ID).terms(
// term -> term
// .value(collect)))
// );
// }
SearchResponse<Knowledge> response = client.search(
s -> s
.index(indexList)
.query(
q -> q
.bool(boolQuery.build()))
.highlight(
h -> h
.preTags(highLightPreTags)
.postTags(highLightPostTags)
.fields(KB_TITLE,hf->hf)
.fields(KB_CONTENT,
hf -> hf
.fragmentSize(200) //匹配字符显示200字符
.numberOfFragments(3)//最多匹配3次
.noMatchSize(200)))
.from((finalCurrentPage-1)*finalPageSize)
.size(finalPageSize)
.sort(
so -> so
.field(
f -> f
.field(KB_UPDATE_TIME).order(SortOrder.Desc)))
,
Knowledge.class
);
HitsMetadata<Knowledge> hitsMetadata = response.hits();
Long total = hitsMetadata.total().value();
List<Hit<Knowledge>> hits = hitsMetadata.hits();
for (Hit<Knowledge> hit : hits) {
Knowledge knowledge = hit.source();
Map<String, List<String>> highlight = hit.highlight();
if (!highlight.isEmpty()){
List<String> title = highlight.get(KB_TITLE);
if(title != null && title.size() > 0){//title高亮
knowledge.setTitle(title.get(0));
}
List<String> content = highlight.get(KB_CONTENT);
if(content != null && content.size() > 0){//content高亮
knowledge.setContent(content.get(0));
}
}
//List<String> sort = hit.sort();
// System.out.println(sort);
// if (sort.size() > 0) {
// String s = sort.get(0);
// Knowledge.setDistance(s);
// }
knowledges.add(knowledge);
}
return total;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* (公共查询)四个搜索条件 关键字 分类 类型(四大类) 来源
* (私人查询:收藏,)
* @param knowledgeVo
*/
public Long selectDocument(List<Knowledge> knowledges,KnowledgeVo knowledgeVo,String index,boolean isHighLight){
try {
String deptId = ThreadLocalUtil.getUserInfo().getDeptId();
Integer finalCurrentPage = knowledgeVo.getCurrentPage();
Integer finalPageSize = knowledgeVo.getPageSize();
//条件查询器
BoolQuery.Builder boolQuery = new BoolQuery.Builder();
if(!StrUtil.isEmpty(knowledgeVo.getKeyword())){
log.info("Keyword不为空 值:{}",knowledgeVo.getKeyword());
boolQuery.must(m->m.multiMatch( mm-> mm
.fields(KB_TITLE,KB_CONTENT)
.query(knowledgeVo.getKeyword())
));
}
List<Long> categoryIds = knowledgeVo.getCategoryIds();
if(null != categoryIds && categoryIds.size() > 0){
log.info("categoryIds不为空 值:{}", knowledgeVo.getCategoryIds());
List<FieldValue> collect = categoryIds.stream().map(FieldValue::of).collect(Collectors.toList());
boolQuery.must(m -> m
.terms(v -> v
.field(KB_CATEGORY_ID).terms(term->term.value(collect)))
);
}
//用户id
if(!StrUtil.isEmpty(knowledgeVo.getCreateById())){
log.info("CreateById不为空 值:{}",knowledgeVo.getCreateById());
boolQuery.must(m -> m
.term(
t -> t
.field(KB_CREATE_BY_ID).value(knowledgeVo.getCreateById())
));
}
//来源
// List<Integer> resources = knowledgeVo.getResources();
// if(null != resources && resources.size()>0){
// log.info("resources不为空 值:{}", knowledgeVo.getResources());
// List<FieldValue> collect = resources.stream().map(FieldValue::of).collect(Collectors.toList());
// boolQuery.must(
// m -> m
// .terms(
// v -> v
// .field(KB_RESOURCE).terms(
// term -> term
// .value(collect)))
// );
// }
// List<Long> knowledgeIds = knowledgeVo.getKnowledgeIds();
//文章id范围查询
// if(null != knowledgeIds && knowledgeIds.size()>0){
// log.info("knowledgeIds不为空 值:{}", knowledgeVo.getKnowledgeIds());
// List<FieldValue> collect = knowledgeIds.stream().map(FieldValue::of).collect(Collectors.toList());
// boolQuery.must(
// m -> m
// .terms(
// v -> v
// .field(KB_ID).terms(
// term -> term
// .value(collect)))
// );
// }
//如果查询私有库 是私有库和公开库一起查询, 而且要加deptId
List<String> indexUmi = new ArrayList<>();
if(COLLLECTION_BASE.equalsIgnoreCase(index)){
indexUmi.add(index);
}else{
indexUmi.add(index);
indexUmi.add(COLLLECTION_BASE);
//本部门查询 查询public中数据要加上部门号
boolQuery.must(m -> m
.term(
t -> t
.field(KB_DEPT_ID).value(deptId)
));
}
log.info("查询索引{}",indexUmi);
SearchResponse<Knowledge> response = client.search(
s -> s
.index(indexUmi)
.query(
q -> q
.bool(boolQuery.build()))
.highlight(
h -> h
.preTags(highLightPreTags)
.postTags(highLightPostTags)
.fields(KB_TITLE,hf->hf)
.fields(KB_CONTENT,
hf -> hf
.fragmentSize(200) //匹配字符显示200字符
.numberOfFragments(3)//最多匹配3次
.noMatchSize(200)))
.from((finalCurrentPage-1)*finalPageSize)
.size(finalPageSize)
.sort(
so -> so
.field(
f -> f
.field(KB_UPDATE_TIME).order(SortOrder.Desc)))
,
Knowledge.class
);
HitsMetadata<Knowledge> hitsMetadata = response.hits();
Long total = hitsMetadata.total().value();
List<Hit<Knowledge>> hits = hitsMetadata.hits();
for (Hit<Knowledge> hit : hits) {
Knowledge knowledge = hit.source();
if(isHighLight){
Map<String, List<String>> highlight = hit.highlight();
if (!highlight.isEmpty()){
List<String> title = highlight.get(KB_TITLE);
if(title != null && title.size() > 0){//title高亮
knowledge.setTitle(title.get(0));
}
List<String> content = highlight.get(KB_CONTENT);
if(content != null && content.size() > 0){//content高亮
knowledge.setContent(content.get(0));
}
}
}
//List<String> sort = hit.sort();
// System.out.println(sort);
// if (sort.size() > 0) {
// String s = sort.get(0);
// Knowledge.setDistance(s);
// }
knowledges.add(knowledge);
}
return total;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 修改 知识的收藏者列表
* @param knowledgeId
* @param users
*/
public void changeCollection(Long knowledgeId, List<String> users,String index){
Map<String, Object> map = new HashMap<>();
map.put(KB_COLLECTION_USERS, users);
try {
client.update(builder -> builder
.index(index)
.id(knowledgeId.toString())
.doc(map),Knowledge.class);
log.info("修改es收藏人列表中文章id为{},index为{}",knowledgeId,index);
} catch (IOException e) {
log.error("修改es收藏人列表中文章id为{},index为{}时报错:{}",knowledgeId,index,e.getMessage());
throw new RuntimeException(e);
}
}
public void changeCategoryId(Long sourceCategoryId, Long destCategoryId, String index){
try {
//"ctx._source."+ KB_CATEGORY_ID +" = 'new_value'"
// Script script = new Script.Builder()
// .inline(i -> i.source())
// .build();
client.updateByQuery( u -> u
.index(index)
.query( q -> q
.term( t -> t
.field(KB_CATEGORY_ID)
.value(sourceCategoryId))
)
.script( s-> s.inline( i -> i
.source("ctx._source." + KB_CATEGORY_ID + "=params.newValue")
.params("newValue", JsonData.of(destCategoryId))
))
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
*
* @param knowledge 里面要有id
*/
public void updateDocument(Knowledge knowledge, String index){
Map<String, Object> map = new HashMap<>();
//更新时间更新者
if(!StrUtil.isEmpty(knowledge.getUpdateById())){
map.put(KB_UPDATE_BY_ID, knowledge.getUpdateById());
}
if(!StrUtil.isEmpty(knowledge.getCreateByName())){
map.put(KB_UPDATE_BY_NAME, knowledge.getUpdateByName());
}
map.put(KB_UPDATE_TIME, knowledge.getUpdateTime());
// 分类id categoryId
if(knowledge.getCategoryId() != null && knowledge.getCategoryId() != Long.MIN_VALUE){
map.put(KB_CATEGORY_ID, knowledge.getCategoryId());
}
if(knowledge.getBaseId() != null && knowledge.getBaseId() != Long.MIN_VALUE){
map.put(KB_BASE_ID, knowledge.getBaseId());
}
//文章内容
if(!StrUtil.isEmpty(knowledge.getContent())){
map.put(KB_CONTENT, cleanHtmlTag(removeHtmlTag(knowledge.getContent(), "style")));
}
if(!StrUtil.isEmpty(knowledge.getTitle())){
map.put(KB_TITLE, knowledge.getTitle());
}
if(!StrUtil.isEmpty(knowledge.getTitle())){
map.put(KB_RESOURCE, knowledge.getResource());
}
if(null != knowledge.getResourcesList() && knowledge.getResourcesList().size() > 0){
map.put(KB_RESOURCES_LIST,knowledge.getResourcesList());
}
// if(knowledge.getTags() != null && knowledge.getTags().size() > 0){
// map.put("tags", knowledge.getTags());
// }
// if(knowledge.getAttachments() != null && knowledge.getAttachments().size() > 0){
// map.put("attachments", knowledge.getAttachments());
// }
try {
client.update(builder -> builder
.index(index)
.id(knowledge.getId().toString())
.doc(map),Knowledge.class);
log.info("修改es中文章id为{},index为{}",knowledge.getId(),index);
} catch (IOException e) {
log.error("修改es中文章id为{},index为{}时报错:{}",knowledge.getId(),index,e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 通过id删除文档
* @param id
*/
public void deleteDocument(Long id,String index){
try {
DeleteResponse delete = client.delete(DeleteRequest.of(h -> h.index(index).id(id.toString())));
log.info("删除es中文章id为{},index为{}",id,index);
} catch (IOException e) {
log.error("删除es中文章id为{},index为{}时报错:{}",id,index,e.getMessage());
throw new RuntimeException(e);
}
}
public void queryIk(String keyword,String index){
}
/**
* 转移索引 从库中转移 并删除原数据
* @param id 数据id
* @param sourceIndex 来源索引
* @param destIndex 转移到的索引
*/
public void transferDocument(Long id,String sourceIndex ,String destIndex){
try {
client.reindex(r -> r
.source(s -> s
.index(sourceIndex)
.query(q -> q.term(
t -> t
.field(KB_ID).value(id)
))
)
.dest(d -> d.index(destIndex))
);
client.deleteByQuery( d -> d
.index(sourceIndex)
.query(
q -> q
.term( m -> m
.field(KB_ID).value(id)
)));
log.info("从{}转移id为{}的文档到{}",sourceIndex,id,destIndex);
} catch (IOException e) {
log.error("从{}转移id为{}的文档到{}报错{}:",sourceIndex,id,destIndex,e.getMessage());
throw new RuntimeException(e);
}
}
public void transferDocumentByBaseId(Long baseId,String sourceIndex ,String destIndex){
try {
client.reindex(r -> r
.source(s -> s
.index(sourceIndex)
.query(q -> q.term(
t -> t
.field(KB_BASE_ID).value(baseId)
))
)
.dest(d -> d.index(destIndex))
);
client.deleteByQuery( d -> d
.index(sourceIndex)
.query(
q -> q
.term( m -> m
.field(KB_BASE_ID).value(baseId)
)));
log.info("从{}转移库id为{}的文档到{}",sourceIndex,baseId,destIndex);
} catch (IOException e) {
log.error("从{}转移库idid为{}的文档到{}报错:{}",sourceIndex,baseId,destIndex,e.getMessage());
throw new RuntimeException(e);
}
}
/**
* 判断索引是否存在
* @param index
* @return
*/
public boolean indexExist(String index){
try {
return client.indices().exists(e -> e.index(index)).value();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 创建索引
*/
public void createIndex(String index){
try {
log.info("es试图创建索引{}", index);
boolean indexExist = client.indices().exists(e -> e.index(index)).value();
if(indexExist) {
log.info("es试图创建索引{},但是已存在", index);
return;
}
CreateIndexResponse createIndexResponse = client.indices()
.create(c -> c
.index(index)
.mappings(m -> m
.dynamic(DynamicMapping.False)
.properties(KB_ID,p -> p.long_( l -> l))
.properties(KB_TITLE, p ->p.text(t -> t.analyzer("ik_max_word").searchAnalyzer("ik_smart")))
.properties(KB_CONTENT, p ->p.text(t -> t.analyzer("ik_smart").searchAnalyzer("ik_smart")))
.properties(KB_CREATE_TIME, p->p.long_(l -> l))
.properties(KB_CREATE_BY_ID, p->p.keyword(k -> k))
.properties(KB_DEPT_ID, p->p.keyword(k -> k))
.properties(KB_CREATE_BY_NAME, p->p.keyword(k -> k))
.properties(KB_UPDATE_TIME, p->p.long_(l -> l))
.properties(KB_UPDATE_BY_ID, p->p.keyword(k -> k))
.properties(KB_UPDATE_BY_NAME, p->p.keyword(k -> k))
.properties(KB_CATEGORY_ID, p->p.long_(l -> l))
.properties(KB_BASE_ID, p->p.long_(l -> l))
.properties(KB_RESOURCES_LIST, p->p.text(t ->t.fields("keywords", f->f.keyword(k -> k))))
.properties(KB_COLLECTION_USERS, p->p.text(t ->t.fields("keywords", f->f.keyword(k -> k))))
)
);
log.info("es试图创建索引{},结果{}", index,createIndexResponse.acknowledged());
} catch (JsonProcessingException e ) {
throw new RuntimeException(e);
}catch (IOException e){
throw new RuntimeException(e);
}
// indexMapping.put("properties", )
//
// createIndexRequest.mapping();
//
// client.indices().create()
}
}

View File

@ -0,0 +1,26 @@
package com.kb.knowledgebase.modules.file;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private FileService fileService;
@GetMapping("/fileDownload")
public void fileDownload(@RequestParam("path") String path, HttpServletResponse response){
fileService.fileDownload(path,response);
}
}

View File

@ -0,0 +1,8 @@
package com.kb.knowledgebase.modules.file;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
public interface FileService {
void fileDownload(String filePath, HttpServletResponse response);
}

View File

@ -0,0 +1,72 @@
package com.kb.knowledgebase.modules.file;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kb.knowledgebase.modules.common.CommonParam;
import com.kb.knowledgebase.modules.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
@Service
@Slf4j
public class FileServiceImpl implements FileService{
@Autowired
private MinioUtil minioUtil;
@Override
public void fileDownload(String filePath, HttpServletResponse response) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
if (StringUtils.isBlank(filePath)) {
response.setHeader("Content-type", "text/html;charset=UTF-8");
String data = "文件下载失败";
OutputStream ps = response.getOutputStream();
ps.write(data.getBytes("UTF-8"));
return;
}
outputStream = response.getOutputStream();
// 获取文件对象
inputStream = minioUtil.getObject(CommonParam.BUCKET_NAME, filePath);
byte buf[] = new byte[1024];
int length = 0;
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(filePath.substring(filePath.lastIndexOf("/") + 1), "UTF-8"));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
// 输出文件
while ((length = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
log.info("{}下载成功",filePath);
inputStream.close();
} catch (Throwable ex) {
response.setHeader("Content-type", "text/html;charset=UTF-8");
String data = "文件下载失败";
try {
OutputStream ps = response.getOutputStream();
ps.write(data.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
outputStream.close();
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,82 @@
package com.kb.knowledgebase.modules.knowledge.callable;
import com.kb.knowledgebase.modules.common.CommonParam;
import com.kb.knowledgebase.modules.util.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
@Slf4j
public class Pdf2ImgCallable implements Callable<List<String>> {
private MinioUtil minioUtil;
private final List<Integer> pageList;
private final String filePath;
private float scale = 300/72f;
public Pdf2ImgCallable(List<Integer> pageList,String filePath,MinioUtil minioUtil){
this.pageList = pageList;
this.filePath = filePath;
this.minioUtil = minioUtil;
}
@Override
public List<String> call() {
List<String> filepaths = new ArrayList<>();
log.info("处理{}",pageList.toString());
try (PDDocument document = Loader.loadPDF(new File(filePath))){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (Integer i : pageList) {
BufferedImage image = null;
try {
image = pdfRenderer.renderImage(i, scale);
} catch (IOException e) {
throw new RuntimeException(e);
}
// String outputImagePath = "d:/20221121/3pdf/" + (i + 1) + ".png";
// try {
// ImageIO.write(image, "PNG", new File(outputImagePath));
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//String fileName = UUID.randomUUID().toString();
String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())
+ UUID.randomUUID().toString().replaceAll("-", "")
+".png"
;
InputStream inputStream = bufferedImageToInputStream(image);
minioUtil.uploadFile("knowledge",objectName,inputStream);
filepaths.add(objectName);
}
log.info("处理完成{}",pageList.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return filepaths;
}
public static InputStream bufferedImageToInputStream(BufferedImage image) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", outputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new ByteArrayInputStream(outputStream.toByteArray());
}
}

View File

@ -0,0 +1,48 @@
package com.kb.knowledgebase.modules.knowledge.constant;
/**
* 分类常量
*
* @author quangz
* @version 1.0
*/
public interface CategoryConstants {
/*分类串分隔符*/
String CATEGORY_FULL_NAME_SEPARATOR = "/";
/*根目录节点ID*/
int ROOT_PID = 0;
/*分类类别0本部门*/
Integer OWN_DEPT = 0;
/*分类类别1公开部门*/
Integer PUB_DEPT = 1;
/*列名id*/
String ID = "id";
/*列名:更新时间*/
String UPDATE_TIME = "update_time";
/*列名:更新者*/
String UPDATE_BY_ID = "update_by_id";
/*知识查询-根节点名称:全部*/
String ROOT_NAME_ALL = "全部";
/*知识查询-根节点id-1*/
Long ROOT_ID_ALL = (long) -1;
/*格式:#0.00*/
String FORMAT_DECIMAL = "#0.00";
/*0占比0.00*/
String DEFAULT_PROPORTION = "0.00";
/*合计初期值0*/
int BASE_TOTAL = 0;
}

View File

@ -0,0 +1,19 @@
package com.kb.knowledgebase.modules.knowledge.constant;
/**
* 主题库常量
*
* @author quangz
* @version 1.0
*/
public interface KbBaseConstants {
/*是否公开:1 公开*/
int IS_PUBLIC_PUB = 1;
/*错误信息:删除主题库时还存在知识关联*/
String BASE_ASSOCIATION_MSG = "此主题库下有关联的分类或知识,不可以删除。";
/*错误信息:主题库名字重复*/
String BASENAME_REPEAT_MSG = "主题库名称重复,请重新输入。";
}

View File

@ -0,0 +1,36 @@
package com.kb.knowledgebase.modules.knowledge.constant;
import cn.hutool.core.map.MapUtil;
/**
* 知识常量
*
* @author quangz
* @version 1.0
*/
public interface KnowledgeConstants {
/**
* 完整分类串
*/
String CATEGORY_FULL_NAME = "category_full_name";
/**
* 收藏数量
*/
String COLLECTION_NUM = "collection_num";
/**
* 浏览量
*/
String VIEW_NUM = "view_num";
/**
* 库名
*/
String BASE_NAME = "base_name";
/**
* 本人是否收藏
*/
String IS_COLLECTION = "is_collection";
String RESOURCE = "resource";
}

View File

@ -0,0 +1,13 @@
package com.kb.knowledgebase.modules.knowledge.constant;
/**
* 我的常量
*
* @author quangz
* @version 1.0
*/
public interface MineConstants {
/*内容截取长度(画面显示概要长度)*/
int CONTENT_LENGTH = 500;
}

View File

@ -0,0 +1,17 @@
package com.kb.knowledgebase.modules.knowledge.constant;
/**
* 来源常量
*
* @author quangz
* @version 1.0
*/
public interface ResourceConstants {
/*错误信息:来源重复*/
String RESOURCE_REPEAT_MSG = "来源名称重复,请重新输入。";
/*错误信息:删除来源时还存在知识关联*/
String RESOURCE_ASSOCIATION_MSG = "目前还有其他知识关联此来源,不能删除";
}

View File

@ -0,0 +1,17 @@
package com.kb.knowledgebase.modules.knowledge.constant;
/**
* 标签常量
*
* @author quangz
* @version 1.0
*/
public interface TagConstants {
/*错误信息:标签重复*/
String TAG_REPEAT_MSG = "标签名称重复,请重新输入。";
/*错误信息:删除标签时还存在知识关联*/
String TAG_ASSOCIATION_MSG = "目前还有其他知识关联此标签,不能删除";
}

View File

@ -0,0 +1,48 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kb.knowledgebase.entity.knowledge.Attachment;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.knowledge.service.IAttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Api(tags = {"附件操作"})
@RestController
@RequestMapping("/attachment")
public class AttachmentController extends BaseController {
@Autowired
private IAttachmentService attachmentService;
@ApiOperation("附件基本操作-分页")
@PostMapping("/query/page")
public ResponseResult queryAttachmentPage(@RequestBody Attachment attachment){
IPage<Attachment> attachmentIPage = attachmentService.queryAttachmentPage(attachment);
return result(attachmentIPage);
}
@ApiOperation("附件基本操作-新增")
@PostMapping("/add")
public ResponseResult<Attachment> addAttachment(@RequestParam("file") MultipartFile file){
Attachment attachment = attachmentService.addAttachment(file);
return result(attachment);
}
@ApiOperation("附件基本操作-删除")
@PostMapping("/delete")
public ResponseResult deleteAttachment(@RequestBody List<Object> list){
System.out.println(list);
// attachmentService.deleteAttachment(attachment);
return result();
}
}

View File

@ -0,0 +1,73 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.kb.knowledgebase.entity.knowledge.Category;
import com.kb.knowledgebase.entity.knowledge.StatisticsCategoryResult;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.ICategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.*;
@Api(tags = {"知识库-知识类别设置"})
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController {
@Autowired
private ICategoryService iCategoryService;
@SysLog(value = "知识库-知识类别设置-查询", type = QUERY)
@ApiOperation("知识库-知识类别设置-查询")
@PostMapping(value = "/selectCategory")
public ResponseResult<List<Category>> selectCategory(@RequestBody Category category) {
List<Category> categoryList = iCategoryService.selectCategoryList(category);
return result(categoryList);
}
@SysLog(value = "知识库-知识类别设置-创建分类", type = ADD)
@ApiOperation("知识库-知识类别设置-创建分类")
@PostMapping(value = "/addCategory")
public ResponseResult addCategory(@RequestBody Category category) {
iCategoryService.addCategory(category);
return result();
}
@SysLog(value = "知识库-知识类别设置-编辑分类", type = UPDATE)
@ApiOperation("知识库-知识类别设置-编辑分类")
@PostMapping(value = "/updateCategory")
public ResponseResult updateCategory(@RequestBody Category category) {
iCategoryService.updateCategory(category);
return result();
}
@SysLog(value = "知识库-知识类别设置-删除分类", type = DELETE)
@ApiOperation("知识库-知识类别设置-删除分类")
@PostMapping(value = "/deleteCategory")
public ResponseResult deleteCategory(@RequestBody Category category) {
iCategoryService.deleteCategory(category);
return result();
}
@SysLog(value = "知识库-知识查询-分类树", type = QUERY)
@ApiOperation("知识库-知识查询-分类树")
@GetMapping(value = "/selectKnowledgeCategoryList")
public ResponseResult<List<Category>> selectKnowledgeCategoryList(@RequestParam Integer categoryType) {
return result(iCategoryService.selectKnowledgeCategoryList(categoryType));
}
@SysLog(value = "知识库-知识统计-分类统计", type = QUERY)
@ApiOperation("知识库-知识统计-分类统计")
@GetMapping(value = "/selectCategoryStatistics")
public ResponseResult<StatisticsCategoryResult> selectCategoryStatistics(@RequestParam Long baseId) {
return result(iCategoryService.selectCategoryStatistics(baseId));
}
}

View File

@ -0,0 +1,70 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.kb.knowledgebase.entity.knowledge.KnowledgeBase;
import com.kb.knowledgebase.entity.knowledge.StatisticsKnowledgeResult;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.IKnowledgeBaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.*;
@Api(tags = {"知识库-主题库"})
@RestController
@RequestMapping("/knowledgeBase")
public class KnowledgeBaseController extends com.kb.knowledgebase.modules.common.BaseController {
@Autowired
private IKnowledgeBaseService iKnowledgeBaseService;
@SysLog(value = "知识库-主题库-查询", type = QUERY)
@ApiOperation("知识库-主题库-查询")
@GetMapping(value = "/selectKnowledgeBase")
public ResponseResult<List<KnowledgeBase>> selectKnowledgeBase() {
return result(iKnowledgeBaseService.selectKnowledgeBaseList());
}
@SysLog(value = "知识库-主题库-添加", type = ADD)
@ApiOperation("知识库-主题库-添加")
@PostMapping(value = "/addKnowledgeBase")
public ResponseResult addKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
iKnowledgeBaseService.addKnowledgeBase(knowledgeBase);
return result();
}
@SysLog(value = "知识库-主题库-更新", type = UPDATE)
@ApiOperation("知识库-主题库-更新")
@PostMapping(value = "/updateKnowledgeBase")
public ResponseResult updateKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
iKnowledgeBaseService.updateKnowledgeBase(knowledgeBase);
return result();
}
@SysLog(value = "知识库-主题库-删除", type = DELETE)
@ApiOperation("知识库-主题库-删除")
@GetMapping(value = "/deleteKnowledgeBase")
public ResponseResult deleteKnowledgeBase(@RequestParam Long id) {
iKnowledgeBaseService.deleteKnowledgeBase(id);
return result();
}
@SysLog(value = "知识库-知识统计-部门知识统计", type = QUERY)
@ApiOperation("知识库-知识统计-部门知识统计")
@GetMapping(value = "/deptKnowledgeStatistics")
public ResponseResult<StatisticsKnowledgeResult> deptKnowledgeStatistics() {
return result(iKnowledgeBaseService.deptKnowledgeStatistics());
}
@SysLog(value = "知识库-知识统计-公开知识统计", type = QUERY)
@ApiOperation("知识库-知识统计-公开知识统计")
@GetMapping(value = "/pubDeptKnowledgeStatistics")
public ResponseResult<StatisticsKnowledgeResult> pubDeptKnowledgeStatistics() {
return result(iKnowledgeBaseService.pubDeptKnowledgeStatistics());
}
}

View File

@ -0,0 +1,165 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeComment;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.elasticsearch.impl.ElasticSearchServiceImpl;
import com.kb.knowledgebase.modules.knowledge.service.IKnowledgeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import static cn.hutool.http.HtmlUtil.removeHtmlTag;
@Api(tags = {"知识库基本操作"})
@RestController
@RequestMapping("/knowledge")
public class KnowledgeController extends BaseController {
@Autowired
private IKnowledgeService iKnowledgeService;
/**
* 基于elasticSearch查询
* @param knowledge
* @return
*/
@SysLog(value = "知识库-知识管理-知识查询", type = "query")
@ApiOperation("知识库基本操作-分页")
@PostMapping("/query/page")
public ResponseResult<List<Knowledge>> queryKnowledgePage(@RequestBody KnowledgeVo knowledge){
List<Knowledge> knowledgeList = new ArrayList<>();
Long total = iKnowledgeService.queryKnowledgePage(knowledge,knowledgeList);
return result(knowledgeList,new Long(knowledge.getCurrentPage()),new Long(knowledge.getPageSize()),total);
}
@SysLog(value = "知识库-知识管理-用户收藏知识查询", type = "query")
@ApiOperation("知识库基本操作-查询收藏内知识")
@PostMapping("/collection/query/page")
public ResponseResult<List<Knowledge>> queryCollectionKnowledgePage(@RequestBody KnowledgeVo knowledge){
List<Knowledge> knowledgeList = new ArrayList<>();
Long total = iKnowledgeService.queryCollectionKnowledgePage(knowledge,knowledgeList);
return result(knowledgeList,new Long(knowledge.getCurrentPage()),new Long(knowledge.getPageSize()),total);
}
@SysLog(value = "知识库-知识管理-主题库内知识查询", type = "query")
@ApiOperation("知识库基本操作-分页 库内知识 不走es查询 ")
@PostMapping("/base/query/page")
public ResponseResult<Knowledge> queryKnowledgePageByBaseId(@RequestBody KnowledgeVo knowledge){
IPage<Knowledge> knowledgeIPage = iKnowledgeService.queryKnowledgePageByBaseId(knowledge);
return result(knowledgeIPage);
}
@SysLog(value = "知识库-知识管理-知识新增", type = "add")
@ApiOperation("知识库基本操作-新增")
@PostMapping("/add")
public ResponseResult addKnowledge(@RequestBody Knowledge knowledge){
iKnowledgeService.addKnowledge(knowledge);
return result();
}
@SysLog(value = "知识库-知识管理-知识删除", type = "delete")
@ApiOperation("知识库基本操作-删除")
@PostMapping("/delete")
public ResponseResult knowledgeDelete(@RequestBody Knowledge knowledge){
iKnowledgeService.deleteKnowledge(knowledge);
return result();
}
@SysLog(value = "知识库-知识管理-知识更新", type = "update")
@ApiOperation("知识库基本操作-更新")
@PostMapping("/update")
public ResponseResult knowledgeUpdate(@RequestBody Knowledge knowledge){
iKnowledgeService.updateKnowledge(knowledge);
return result();
}
@SysLog(value = "知识库-知识管理-知识详情", type = "detail")
@ApiOperation("知识库基本操作-详细")
@PostMapping("/detail")
public ResponseResult<Knowledge> getKnowledgeDetail(@RequestBody Knowledge knowledge)
{
Knowledge res = iKnowledgeService.getKnowledgeDetail(knowledge);
return result(res);
}
@SysLog(value = "知识库-知识管理-上架下架知识", type = "update")
@ApiOperation("知识库基本操作-上架 下架")
@PostMapping("/publishKnowledge")
public ResponseResult publishKnowledge(@RequestBody Knowledge knowledge){
iKnowledgeService.publishKnowledge(knowledge);
return result();
}
@SysLog(value = "知识库-知识管理-知识转移", type = "update")
@ApiOperation("知识库基本操作-转移")
@PostMapping("/transferKnowledge")
public ResponseResult transferKnowledge(@RequestBody Knowledge knowledge) {
iKnowledgeService.transferKnowledge(knowledge);
return result();
}
/**
* 最新知识排行
* @return
*/
@SysLog(value = "知识库-知识管理-主题库内知识查询", type = "query")
@GetMapping("/selectNewKnowledgeRanking")
public ResponseResult newKnowledgeRanking(){
return result(iKnowledgeService.newKnowledgeRanking());
}
/**
* 最热知识排行
* @return
*/
@SysLog(value = "知识库-知识管理-热门知识排行", type = "query")
@GetMapping("/selectHotKnowledgeRanking")
public ResponseResult hotKnowledgeRanking(){
return result(iKnowledgeService.hotKnowledgeRanking());
}
@SysLog(value = "知识库-知识管理-知识推荐", type = "query")
@GetMapping("/recommend")
public ResponseResult recommend(){return result(iKnowledgeService.recommend());}
/**
* 上传minio并生成外链
* @param file
* @return
*/
@SysLog(value = "知识库-知识管理-上传文件转换", type = "add")
@PostMapping("/upload/file")
public ResponseResult<Map<String,Object>> uploadKnowledge(@RequestParam("file") MultipartFile file) {
Map<String,Object> s = iKnowledgeService.uploadKnowledge(file);
return result(s);
}
/**
* 关键词热词
* @return
*/
@SysLog(value = "知识库-知识管理-热门关键词", type = "query")
@GetMapping("/keywordRanking")
public ResponseResult getkeywordsRanking(){
Set<ZSetOperations.TypedTuple<String>> typedTuples = iKnowledgeService.getkeywordsRanking();
return result(typedTuples);
}
@GetMapping("/fileDownload")
public void fileDownload(@RequestParam("path") String path, HttpServletResponse response){
iKnowledgeService.fileDownload(path,response);
}
}

View File

@ -0,0 +1,83 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeCollection;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.IKnowledgeCollectionService;
import com.kb.knowledgebase.modules.knowledge.service.IKnowledgeService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.*;
@Api(tags = {"知识库-我的"})
@RestController
@RequestMapping("/mine")
public class MineController extends BaseController {
@Autowired
private IKnowledgeCollectionService iKnowledgeCollectionService;
@Autowired
private IKnowledgeService iKnowledgeService;
// @ApiOperation("知识库-我的-我的评论-初期查询")
// @PostMapping(value = "/selectKnowledgeComment")
// public ResponseResult<List<KnowledgeComment>> selectKnowledgeComment(@RequestParam String userId) {
// return result(iKnowledgeCommentService.selectKnowledgeComment(userId));
// }
//
// @ApiOperation("知识库-我的-我的评论-编辑")
// @PostMapping(value = "/updateKnowledgeComment")
// public ResponseResult updateKnowledgeComment(@RequestParam Long id, @RequestParam String comment) {
// iKnowledgeCommentService.updateKnowledgeComment(id,comment);
// return result();
// }
//
// @ApiOperation("知识库-我的-我的评论-删除")
// @PostMapping(value = "/deleteKnowledgeComment")
// public ResponseResult deleteKnowledgeComment(@RequestParam Long id) {
// iKnowledgeCommentService.deleteKnowledgeComment(id);
// return result();
// }
@SysLog(value = "知识库-我的收藏-初期查询", type = QUERY)
@ApiOperation("知识库-我的收藏-初期查询")
@PostMapping(value = "/selectKnowledgeCollection")
public ResponseResult<List<Knowledge>> selectKnowledgeCollection(@RequestBody KnowledgeVo knowledge) {
if (StringUtil.isNullOrEmpty(knowledge.getKeyword())) {
IPage<Knowledge> page = iKnowledgeCollectionService.selectKnowledgeCollection(knowledge);
return result(page.getRecords(),new Long(knowledge.getCurrentPage()),new Long(knowledge.getPageSize()),page.getTotal());
} else {
List<Knowledge> knowledgeList = new ArrayList<>();
Long total = iKnowledgeService.queryCollectionKnowledgePage(knowledge,knowledgeList);
return result(knowledgeList,new Long(knowledge.getCurrentPage()),new Long(knowledge.getPageSize()),total);
}
}
@SysLog(value = "知识库-我的收藏-取消收藏", type = DELETE)
@ApiOperation("知识库-我的收藏-取消收藏")
@GetMapping(value = "/cancelKnowledgeCollection")
public ResponseResult cancelKnowledgeCollection(@RequestParam Long id) {
iKnowledgeCollectionService.cancelKnowledgeCollection(id);
return result();
}
@SysLog(value = "知识库-我的收藏-添加收藏", type = ADD)
@ApiOperation("知识库-我的收藏-添加收藏")
@GetMapping(value = "/addKnowledgeCollection")
public ResponseResult addKnowledgeCollection(@RequestParam Long kid) {
iKnowledgeCollectionService.addKnowledgeCollection(kid);
return result();
}
}

View File

@ -0,0 +1,47 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.kb.knowledgebase.entity.knowledge.Resource;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.IResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.*;
@Api(tags = {"知识库-来源管理"})
@RestController
@RequestMapping("/resource")
public class ResourceController extends BaseController {
@Autowired
private IResourceService iResourceService;
@SysLog(value = "知识库-来源管理-来源查询/刷新", type = QUERY)
@ApiOperation("知识库-来源管理-来源查询/刷新")
@GetMapping(value = "/selectResource")
public ResponseResult<List<Resource>> selectResource(@RequestParam String resourceName) {
return result(iResourceService.selectResourceList(resourceName));
}
@SysLog(value = "知识库-来源管理-添加来源", type = ADD)
@ApiOperation("知识库-来源管理-添加来源")
@PostMapping(value = "/addResource")
public ResponseResult addResource(@RequestBody Resource resource) {
iResourceService.addResource(resource);
return result();
}
@SysLog(value = "知识库-来源管理-删除来源", type = DELETE)
@ApiOperation("知识库-来源管理-删除来源")
@GetMapping(value = "/deleteResource")
public ResponseResult deleteResource(@RequestParam Long id) {
iResourceService.deleteResource(id);
return result();
}
}

View File

@ -0,0 +1,88 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.kb.knowledgebase.entity.knowledge.StatisticsResult;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.IStatisticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.QUERY;
@Api(tags = {"知识库-数量统计"})
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {
@Autowired
private IStatisticsService statisticsService;
/**
* 全平台接口统计
* @return
*/
@SysLog(value = "知识库-类别统计-查询", type = QUERY)
@ApiOperation("知识库-类别统计-查询")
@GetMapping(value = "/queryTypeStatistics")
public ResponseResult<List<StatisticsResult>> queryTypeStatistics(){
return result(statisticsService.queryTypeStatistics());
}
@SysLog(value = "知识库-来源统计-查询", type = QUERY)
@ApiOperation("知识库-来源统计-查询")
@GetMapping(value = "/queryResourceStatistics")
public ResponseResult<List<StatisticsResult>> queryResourceStatistics(){
return result(statisticsService.queryResourceStatistics());
}
@SysLog(value = "知识库-大类统计-查询", type = QUERY)
@ApiOperation("知识库-大类统计-查询")
@GetMapping(value = "/queryCategoryStatistics")
public ResponseResult<List<StatisticsResult>> queryCategoryStatistics(){
return result(statisticsService.queryCategoryStatistics());
}
@SysLog(value = "知识库-库-查询", type = QUERY)
@ApiOperation("知识库-库-查询")
@GetMapping(value = "/queryBaseCount")
public ResponseResult queryBaseCount(@RequestParam("is_public") Integer isPublic){
return result(statisticsService.queryBaseCount(isPublic));
}
@SysLog(value = "知识库-知识概览-部门知识概览", type = QUERY)
@ApiOperation("知识库-知识概览-部门知识概览")
@GetMapping(value = "/deptKnowledgeStatistics")
public ResponseResult<List<StatisticsResult>> deptKnowledgeStatistics(){
return result(statisticsService.deptKnowledgeStatistics());
}
@SysLog(value = "知识库-知识概览-部门主题库概览(饼图)", type = QUERY)
@ApiOperation("知识库-知识概览-部门主题库概览(饼图)")
@GetMapping(value = "/deptBaseStatistics")
public ResponseResult<List<StatisticsResult>> deptBaseStatistics(){
return result(statisticsService.deptBaseStatistics());
}
@SysLog(value = "知识库-知识概览-部门知识来源概览", type = QUERY)
@ApiOperation("知识库-知识概览-部门知识来源概览")
@GetMapping(value = "/deptResourceStatistics")
public ResponseResult<List<StatisticsResult>> deptResourceStatistics(){
return result(statisticsService.deptResourceStatistics());
}
@SysLog(value = "知识库-知识概览-公开知识概览", type = QUERY)
@ApiOperation("知识库-知识概览-公开知识概览")
@GetMapping(value = "/pubKnowledgeStatistics")
public ResponseResult<List<StatisticsResult>> pubKnowledgeStatistics(){
return result(statisticsService.pubKnowledgeStatistics());
}
}

View File

@ -0,0 +1,48 @@
package com.kb.knowledgebase.modules.knowledge.controller;
import com.kb.knowledgebase.entity.knowledge.Tag;
import com.kb.knowledgebase.modules.common.BaseController;
import com.kb.knowledgebase.modules.common.ResponseResult;
import com.kb.knowledgebase.modules.common.log.annotation.SysLog;
import com.kb.knowledgebase.modules.knowledge.service.ITagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.kb.knowledgebase.modules.common.log.constant.SysLogTypeConstants.*;
@Api(tags = {"知识库-标签管理"})
@RestController
@RequestMapping("/tag")
public class TagController extends BaseController {
@Autowired
private ITagService iTagService;
@SysLog(value = "知识库-标签管理-标签查询/刷新", type = QUERY)
@ApiOperation("知识库-标签管理-标签查询/刷新")
@GetMapping(value = "/selectTag")
public ResponseResult<List<Tag>> selectTag(@RequestParam String tagName) {
return result(iTagService.selectTagList(tagName));
}
@SysLog(value = "知识库-标签管理-添加标签", type = ADD)
@ApiOperation("知识库-标签管理-添加标签")
@PostMapping(value = "/addTag")
public ResponseResult addTag(@RequestBody Tag tag) {
iTagService.addTag(tag);
return result();
}
@SysLog(value = "知识库-标签管理-删除标签", type = DELETE)
@ApiOperation("知识库-标签管理-删除标签")
@GetMapping(value = "/deleteTag")
public ResponseResult deleteTag(@RequestParam Long id) {
iTagService.deleteTag(id);
return result();
}
}

View File

@ -0,0 +1,13 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.knowledgebase.entity.knowledge.Attachment;
import org.apache.ibatis.annotations.Param;
public interface AttachmentMapper extends BaseMapper<Attachment> {
IPage<Attachment> queryAttachmentPage(Page<?> page, @Param("param") Attachment attachment);
}

View File

@ -0,0 +1,34 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.Category;
import com.kb.knowledgebase.entity.knowledge.StatisticsResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CategoryMapper extends BaseMapper<Category> {
/**
* 知识类别设置-查询
* @param category 分类查询条件
* @return 结果集
*/
List<Category> selectCategoryList(Category category);
/**
* 知识概览-知识大类统计
* @return 结果集
*/
List<StatisticsResult> selectOneLevelStatistics();
/**
* 获取子级ID包含自ID
* @param pid 父id
* @return 结果集
*/
List<Category> selectCategoryListByPid(@Param("pid") Long pid);
}

View File

@ -0,0 +1,19 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.kb.knowledgebase.entity.knowledge.KnowledgeBase;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface KnowledgeBaseMapper extends com.baomidou.mybatisplus.core.mapper.BaseMapper<KnowledgeBase> {
/**
* 主题库-查询
*
* @param deptId 部门id
* @return 结果集
*/
List<KnowledgeBase> selectKnowledgeBaseList(String deptId);
}

View File

@ -0,0 +1,34 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeCollection;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface KnowledgeCollectionMapper extends BaseMapper<KnowledgeCollection> {
/**
* 我的-我的收藏-初期查询
*
* @param knowledge 收藏
* @return 结果集
*/
IPage<Knowledge> selectKnowledgeCollection(Page<?> page , @Param("param") KnowledgeVo knowledge);
/**
* 查询收藏用户List
*
* @param kid 收藏
* @return 结果集
*/
List<String> selectCollectionUserList(Long kid);
List<Map<String,Object>> queryResources(@Param("list") List<Long> list);
}

View File

@ -0,0 +1,20 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.KnowledgeComment;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface KnowledgeCommentMapper extends BaseMapper<KnowledgeComment> {
/**
* 我的-我的评论-初期查询
*
* @param userId 用户id
* @return 结果集
*/
List<KnowledgeComment> selectKnowledgeComment(@Param("userId")String userId);
}

View File

@ -0,0 +1,94 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeBase;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface KnowledgeMapper extends BaseMapper<Knowledge> {
IPage<Knowledge> queryKnowledgePage(Page<?> page , @Param("param") Knowledge knowledge);
IPage<Knowledge> queryKnowledgePageByBaseId(Page<?> page , @Param("param") KnowledgeVo knowledge);
List<Map<String,Object>> queryResources(@Param("list") List<Long> list);
List<Map<String,Object>> queryAddtionalData(@Param("userId") String userId,@Param("list") List<Long> list);
int getBaseCount(@Param("deptId") String deptId);
List<Knowledge> queryKnowledgePage(@Param("param") Knowledge knowledge);
List<Knowledge> newKnowledgeRanking(@Param("num") int number);
List<Knowledge> hotKnowledgeRanking(@Param("num") int number);
List<Knowledge> hotKnowledgeRanking1(@Param("num") int number, @Param("list") List<Long> list);
List<Map<String, String>> queryTotal(@Param("type") String type);
void addKnowledgeTags(@Param("list") List<Long> list, @Param("id") Long id);
void deleteKnowledgeTags(@Param("id") Long id);
void addKnowledgeResource(@Param("list") List<Long> list, @Param("id") Long id);
void deleteKnowledgeResource(@Param("id") Long id);
void addKnowledgeContent(@Param("id")Long id, @Param("content") String content);
void updateKnowledgeContent(@Param("id")Long id, @Param("content") String content);
void deleteKnowledgeContent(@Param("id")Long id);
void addKnowledgeImgPaths(@Param("id")Long id, @Param("list") List<String> imgPaths);
void deleteKnowledgeImgPaths(@Param("id")Long id);
void addKnowledgeAttachments(@Param("list") List<Integer> list, @Param("id") Long id);
List<String> selectKnowledgeImgPaths(@Param("id") Long id);
KnowledgeBase queryKnowledgeDeptId(@Param("id") Long id);
KnowledgeBase queryDeptIdByKnowledgeId(@Param("id") Long id);
Knowledge getKnowledgeDetail(@Param("id") Long id,@Param("userId") String userId);
String getContentById(@Param("id") Long id);
void incrViewNum(@Param("id") Long id);
List<Map<String, String>>selectTagsById(@Param("id") Long id);
List<Map<String, String>>selectResourcesById(@Param("id") Long id);
//库内知识量+1
void incrBaseKbCount(@Param("id") Long id);
//分类知识量+1
void incrCategoryKbCount(@Param("id") Long id);
void decrBaseKbCount(@Param("id") Long id);
//分类知识量+1
void decrCategoryKbCount(@Param("id") Long id);
//查询用户收藏列表 做查询用
List<Long> getColletionListByUserId(@Param("userId") String id);
void isTransfer(Long sourceBaseId, Long destBaseId);
}

View File

@ -0,0 +1,10 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.KnowledgeResource;
import org.springframework.stereotype.Repository;
@Repository
public interface KnowledgeResourceMapper extends BaseMapper<KnowledgeResource> {
}

View File

@ -0,0 +1,10 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.KnowledgeTag;
import org.springframework.stereotype.Repository;
@Repository
public interface KnowledgeTagMapper extends BaseMapper<KnowledgeTag> {
}

View File

@ -0,0 +1,20 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.Resource;
import com.kb.knowledgebase.entity.knowledge.StatisticsResult;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ResourceMapper extends BaseMapper<Resource> {
/**
* 来源管理-来源查询
*
* @param resourceName 来源名称
* @return 结果集
*/
List<Resource> selectResourceList(String resourceName);
}

View File

@ -0,0 +1,12 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.SearchHistory;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface SearchHistoryMapper extends BaseMapper<SearchHistory> {
String searchHotWords(@Param("userId") String userId);
}

View File

@ -0,0 +1,39 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.StatisticsResult;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface StatisticsMapper extends BaseMapper<String> {
Map<String, Long> queryTypeStatistics();
Map<String, Long> queryResourceStatistics();
/**
* 部门知识概览
*
* @param deptId 部门id
* @return 统计结果
*/
Map<String, Long> deptKnowledgeStatistics(String deptId);
/**
* 部门知识概览
*
* @param deptId 部门id
* @return 统计结果
*/
List<StatisticsResult> deptResourceStatistics(String deptId);
/**
* 公开知识概览
*
* @return 统计结果
*/
Map<String, Long> pubKnowledgeStatistics();
}

View File

@ -0,0 +1,20 @@
package com.kb.knowledgebase.modules.knowledge.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kb.knowledgebase.entity.knowledge.Tag;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TagMapper extends BaseMapper<Tag> {
/**
* 标签管理-标签查询
*
* @param tagName 类别名称
* @return 结果集
*/
List<Tag> selectTagList(String tagName);
}

View File

@ -0,0 +1,15 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.Attachment;
import org.springframework.web.multipart.MultipartFile;
public interface IAttachmentService extends IService<Attachment> {
IPage<Attachment> queryAttachmentPage(Attachment attachment);
Attachment addAttachment(MultipartFile file);
void deleteAttachment(Attachment attachment);
}

View File

@ -0,0 +1,67 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.Category;
import com.kb.knowledgebase.entity.knowledge.StatisticsCategoryResult;
import com.kb.knowledgebase.entity.knowledge.StatisticsResult;
import java.util.List;
public interface ICategoryService extends IService<Category> {
/**
* 知识类别设置-查询
*
* @param category 分类查询条件
* @return 结果集
*/
List<Category> selectCategoryList(Category category);
/**
* 知识类别设置-创建分类
*
* @param category 分类
*/
void addCategory(Category category);
/**
* 知识类别设置-编辑分类
*
* @param category 分类
*/
void updateCategory(Category category);
/**
* 知识类别设置-删除分类
*
* @param category 分类
*/
void deleteCategory(Category category);
/**
* 知识概览-知识大类统计
* @return 结果集(一级分类名称,知识数量)
*/
List<StatisticsResult> selectOneLevelStatistics();
/**
* 获取子级ID包含自ID
* @param pid 父id
* @return 结果集
*/
List<Category> selectCategoryListByPid(Long pid);
/**
* 知识查询-分类树
* @param categoryType 分类类别 0本部门 1公开部门
* @return 结果集
*/
List<Category> selectKnowledgeCategoryList(Integer categoryType);
/**
* 知识统计-分类统计
*
* @param baseId 分类查询条件
* @return 结果集
*/
StatisticsCategoryResult selectCategoryStatistics(Long baseId);
}

View File

@ -0,0 +1,49 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.KnowledgeBase;
import com.kb.knowledgebase.entity.knowledge.StatisticsKnowledgeResult;
import java.util.List;
public interface IKnowledgeBaseService extends IService<KnowledgeBase> {
/**
* 主题库-查询
*
* @return 结果集
*/
List<KnowledgeBase> selectKnowledgeBaseList();
/**
* 主题库-添加
*
* @param knowledgeBase 主题库信息
*/
void addKnowledgeBase(KnowledgeBase knowledgeBase);
/**
* 主题库-更新
*
* @param knowledgeBase 主题库信息
*/
void updateKnowledgeBase(KnowledgeBase knowledgeBase);
/**
* 主题库-删除
*
* @param id 主题库id
*/
void deleteKnowledgeBase(Long id);
/**
* 部门知识统计
*
*/
StatisticsKnowledgeResult deptKnowledgeStatistics();
/**
* 公开知识统计
*
*/
StatisticsKnowledgeResult pubDeptKnowledgeStatistics();
}

View File

@ -0,0 +1,34 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeCollection;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import java.util.List;
public interface IKnowledgeCollectionService extends IService<KnowledgeCollection> {
/**
* 我的-我的收藏-查询
*
* @param knowledge 收藏
* @return 结果集
*/
IPage<Knowledge> selectKnowledgeCollection(KnowledgeVo knowledge);
/**
* 我的-我的收藏-取消收藏
*
* @param id 收藏id
*/
void cancelKnowledgeCollection(Long id);
/**
* 我的-我的收藏-增加收藏
*
* @param kid 知识id
*/
void addKnowledgeCollection(Long kid);
}

View File

@ -0,0 +1,34 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.KnowledgeComment;
import java.util.List;
public interface IKnowledgeCommentService extends IService<KnowledgeComment> {
/**
* 我的-我的评论-初期查询
*
* @param userId 用户id
* @return 结果集
*/
List<KnowledgeComment> selectKnowledgeComment(String userId);
/**
* 我的-我的评论-编辑
*
* @param id 评论ID
* @param comment 评论内容
*
*/
void updateKnowledgeComment(Long id, String comment);
/**
* 我的-我的评论-删除
*
* @param id 评论ID
*
*/
void deleteKnowledgeComment(Long id);
}

View File

@ -0,0 +1,22 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.KnowledgeResource;
public interface IKnowledgeResourceService extends IService<KnowledgeResource> {
/**
* 查询知识和来源关联
*
* @param resourceId 来源id
*
*/
Long selectKnowledgeResourceCount(Long resourceId);
/**
* 删除知识和来源关联
*
* @param resourceId 来源id
*
*/
void deleteKnowledgeResource(Long resourceId);
}

View File

@ -0,0 +1,62 @@
package com.kb.knowledgebase.modules.knowledge.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kb.knowledgebase.entity.knowledge.Knowledge;
import com.kb.knowledgebase.entity.knowledge.KnowledgeVo;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface IKnowledgeService extends IService<Knowledge> {
Long queryKnowledgePage(KnowledgeVo knowledge,List<Knowledge> knowledges);
void changeCollection(Long knowledgeId, List<String> users);
void changeCategoryId(Long sourceCategoryId, Long destCategoryId,Long baseId);
/*
知识转移接口
1.单独knowledgeId转移 (更新数据库 更新es文档) xxxx没有这个希求
2.分类转移 , 知识全部修改id(更新数据库 更新es文档) xxxx只修改上级分类也不用写,修改自己的分类才需要写
3.修改库 数据更改baseId (更新数据库 es索引值转移) 目前做这个就够了
*/
void transDocumentByBaseId(Long baseId, int isPublic,String deptId);
Long queryCollectionKnowledgePage(KnowledgeVo knowledge, List<Knowledge> knowledges);
IPage<Knowledge> queryKnowledgePageByBaseId(KnowledgeVo knowledge);
Knowledge getKnowledgeDetail(Knowledge knowledge);
void publishKnowledge(Knowledge knowledge);
void transferKnowledge(Knowledge knowledge);
void addKnowledge(Knowledge knowledge);
void updateKnowledge(Knowledge knowledge);
void deleteKnowledge(Knowledge knowledge);
List<Knowledge> newKnowledgeRanking();
List<Knowledge> hotKnowledgeRanking();
List<Knowledge> recommend();
Map<String,Object> uploadKnowledge(MultipartFile file);
Set<ZSetOperations.TypedTuple<String>> getkeywordsRanking();
void createIndex(String deptId);
void fileDownload(String filePath, HttpServletResponse response);
}

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