Просмотр исходного кода

Merge branch 'master' of http://124.70.58.209:3000/ytrd-project-management/purchase

 Conflicts:
	purchase-common/pom.xml
gao.qiang 2 лет назад
Родитель
Сommit
754e8d9b6c
22 измененных файлов с 1265 добавлено и 156 удалено
  1. 0 13
      purchase-admin/pom.xml
  2. 40 0
      purchase-admin/src/main/java/com/ozs/web/controller/base/BaseSupplierController.java
  3. 16 0
      purchase-admin/src/main/java/com/ozs/web/controller/system/SysConfigController.java
  4. 3 0
      purchase-admin/src/main/java/com/ozs/web/controller/system/SysLoginController.java
  5. 71 54
      purchase-admin/src/main/java/com/ozs/web/controller/tool/TestController.java
  6. 16 9
      purchase-admin/src/main/resources/application.yml
  7. 2 1
      purchase-admin/src/main/resources/logback.xml
  8. 32 0
      purchase-common/pom.xml
  9. 29 0
      purchase-common/src/main/java/com/ozs/common/config/ElasticsearchConfig.java
  10. 10 0
      purchase-common/src/main/java/com/ozs/common/core/domain/BaseEntity.java
  11. 649 0
      purchase-common/src/main/java/com/ozs/common/utils/EsUtil.java
  12. 70 0
      purchase-common/src/main/java/com/ozs/common/utils/file/FileUploadUtils.java
  13. 148 79
      purchase-common/src/main/java/com/ozs/common/utils/file/FileUtils.java
  14. 21 0
      purchase-common/src/main/java/com/ozs/common/vo/Attachment.java
  15. 19 0
      purchase-common/src/main/java/com/ozs/common/vo/EsMessage.java
  16. 19 0
      purchase-common/src/main/java/com/ozs/common/vo/FileMessage.java
  17. 19 0
      purchase-system/src/main/java/com/ozs/base/domain/BaseSupplier.java
  18. 21 0
      purchase-system/src/main/java/com/ozs/base/mapper/BaseSupplierMapper.java
  19. 20 0
      purchase-system/src/main/java/com/ozs/base/service/BaseSupplierService.java
  20. 24 0
      purchase-system/src/main/java/com/ozs/base/service/impl/BaseSupplierServiceImpl.java
  21. 9 0
      purchase-system/src/main/java/com/ozs/system/domain/SysConfig.java
  22. 27 0
      purchase-system/src/main/resources/mapper/base/BaseSupplierMapper.xml

+ 0 - 13
purchase-admin/pom.xml

@@ -24,19 +24,6 @@
             <optional>true</optional> <!-- 表示依赖不会传递 -->
         </dependency>
 
-        <!-- swagger3-->
-        <dependency>
-            <groupId>io.springfox</groupId>
-            <artifactId>springfox-boot-starter</artifactId>
-        </dependency>
-
-        <!-- 防止进入swagger页面报类型转换错误,排除3.0.0中的引用,手动增加1.6.2版本 -->
-        <dependency>
-            <groupId>io.swagger</groupId>
-            <artifactId>swagger-models</artifactId>
-            <version>1.6.2</version>
-        </dependency>
-
          <!-- Mysql驱动包 -->
         <dependency>
             <groupId>mysql</groupId>

+ 40 - 0
purchase-admin/src/main/java/com/ozs/web/controller/base/BaseSupplierController.java

@@ -0,0 +1,40 @@
+package com.ozs.web.controller.base;
+
+import com.ozs.common.core.controller.BaseController;
+import com.ozs.common.core.domain.AjaxResult;
+import com.ozs.common.utils.StringUtils;
+import com.ozs.base.domain.BaseSupplier;
+import com.ozs.base.service.BaseSupplierService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * 供应商管理
+ *
+ * @author sunhh
+ */
+@Api("供应商管理")
+@RestController
+@RequestMapping("/base/supplier")
+public class BaseSupplierController extends BaseController {
+
+    @Autowired
+    private BaseSupplierService baseSupplierService;
+
+    @ApiOperation("新增供应商户")
+    @ApiImplicitParams({@ApiImplicitParam(paramType = "body", dataType = "BaseSupplier",
+            name = "req", value = "信息参数", required = true)})
+    @PostMapping("/save")
+    public AjaxResult save(BaseSupplier baseSupplier) {
+        if (StringUtils.isNull(baseSupplier) || StringUtils.isNull(baseSupplier.getSupplierName())) {
+            return error("供应商名称不能为空");
+        }
+        return toAjax(baseSupplierService.insertBaseSupplier(baseSupplier));
+    }
+}

+ 16 - 0
purchase-admin/src/main/java/com/ozs/web/controller/system/SysConfigController.java

@@ -2,6 +2,10 @@ package com.ozs.web.controller.system;
 
 import java.util.List;
 import javax.servlet.http.HttpServletResponse;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiOperation;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.validation.annotation.Validated;
@@ -28,6 +32,7 @@ import com.ozs.system.service.ISysConfigService;
  *
  * @author ruoyi
  */
+@Api("信息操作处理")
 @RestController
 @RequestMapping("/system/config")
 public class SysConfigController extends BaseController
@@ -40,6 +45,7 @@ public class SysConfigController extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('system:config:list')")
     @GetMapping("/list")
+    @ApiOperation("获取参数配置列表")
     public TableDataInfo list(SysConfig config)
     {
         startPage();
@@ -50,6 +56,7 @@ public class SysConfigController extends BaseController
     @Log(title = "参数管理", businessType = BusinessType.EXPORT)
     @PreAuthorize("@ss.hasPermi('system:config:export')")
     @PostMapping("/export")
+    @ApiOperation("参数导出")
     public void export(HttpServletResponse response, SysConfig config)
     {
         List<SysConfig> list = configService.selectConfigList(config);
@@ -62,6 +69,8 @@ public class SysConfigController extends BaseController
      */
     @PreAuthorize("@ss.hasPermi('system:config:query')")
     @GetMapping(value = "/{configId}")
+    @ApiOperation("根据参数编号获取详细信息")
+    @ApiImplicitParam(name = "configId", value = "参数ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
     public AjaxResult getInfo(@PathVariable Long configId)
     {
         return success(configService.selectConfigById(configId));
@@ -71,6 +80,8 @@ public class SysConfigController extends BaseController
      * 根据参数键名查询参数值
      */
     @GetMapping(value = "/configKey/{configKey}")
+    @ApiOperation("根据参数键名查询参数值")
+    @ApiImplicitParam(name = "configKey", value = "参数键名", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
     public AjaxResult getConfigKey(@PathVariable String configKey)
     {
         return success(configService.selectConfigByKey(configKey));
@@ -82,6 +93,7 @@ public class SysConfigController extends BaseController
     @PreAuthorize("@ss.hasPermi('system:config:add')")
     @Log(title = "参数管理", businessType = BusinessType.INSERT)
     @PostMapping
+    @ApiOperation("新增参数配置")
     public AjaxResult add(@Validated @RequestBody SysConfig config)
     {
         if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
@@ -98,6 +110,7 @@ public class SysConfigController extends BaseController
     @PreAuthorize("@ss.hasPermi('system:config:edit')")
     @Log(title = "参数管理", businessType = BusinessType.UPDATE)
     @PutMapping
+    @ApiOperation("修改参数配置")
     public AjaxResult edit(@Validated @RequestBody SysConfig config)
     {
         if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config)))
@@ -114,6 +127,8 @@ public class SysConfigController extends BaseController
     @PreAuthorize("@ss.hasPermi('system:config:remove')")
     @Log(title = "参数管理", businessType = BusinessType.DELETE)
     @DeleteMapping("/{configIds}")
+    @ApiOperation("删除参数配置")
+    @ApiImplicitParam(name = "configIds", value = "参数id集合", required = true, dataType = "Long[]", paramType = "path", dataTypeClass = Long.class)
     public AjaxResult remove(@PathVariable Long[] configIds)
     {
         configService.deleteConfigByIds(configIds);
@@ -126,6 +141,7 @@ public class SysConfigController extends BaseController
     @PreAuthorize("@ss.hasPermi('system:config:remove')")
     @Log(title = "参数管理", businessType = BusinessType.CLEAN)
     @DeleteMapping("/refreshCache")
+    @ApiOperation("刷新参数缓存")
     public AjaxResult refreshCache()
     {
         configService.resetConfigCache();

+ 3 - 0
purchase-admin/src/main/java/com/ozs/web/controller/system/SysLoginController.java

@@ -2,6 +2,8 @@ package com.ozs.web.controller.system;
 
 import java.util.List;
 import java.util.Set;
+
+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.PostMapping;
@@ -40,6 +42,7 @@ public class SysLoginController
      * @param loginBody 登录信息
      * @return 结果
      */
+    @ApiOperation("新增用户")
     @PostMapping("/login")
     public AjaxResult login(@RequestBody LoginBody loginBody)
     {

+ 71 - 54
purchase-admin/src/main/java/com/ozs/web/controller/tool/TestController.java

@@ -1,9 +1,18 @@
 package com.ozs.web.controller.tool;
 
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
+
+import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.ozs.common.config.PurchaseConfig;
+import com.ozs.common.utils.file.FileUploadUtils;
+import com.ozs.common.utils.file.FileUtils;
+import com.ozs.common.vo.EsMessage;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
@@ -21,6 +30,7 @@ import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import io.swagger.annotations.ApiOperation;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * swagger 用户测试方法
@@ -30,9 +40,9 @@ import io.swagger.annotations.ApiOperation;
 @Api("用户信息管理")
 @RestController
 @RequestMapping("/test/user")
-public class TestController extends BaseController
-{
+public class TestController extends BaseController {
     private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
+
     {
         users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
         users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
@@ -40,8 +50,7 @@ public class TestController extends BaseController
 
     @ApiOperation("获取用户列表")
     @GetMapping("/list")
-    public R<List<UserEntity>> userList()
-    {
+    public R<List<UserEntity>> userList() {
         List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
         return R.ok(userList);
     }
@@ -49,30 +58,24 @@ public class TestController extends BaseController
     @ApiOperation("获取用户详细")
     @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
     @GetMapping("/{userId}")
-    public R<UserEntity> getUser(@PathVariable Integer userId)
-    {
-        if (!users.isEmpty() && users.containsKey(userId))
-        {
+    public R<UserEntity> getUser(@PathVariable Integer userId) {
+        if (!users.isEmpty() && users.containsKey(userId)) {
             return R.ok(users.get(userId));
-        }
-        else
-        {
+        } else {
             return R.fail("用户不存在");
         }
     }
 
     @ApiOperation("新增用户")
     @ApiImplicitParams({
-        @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
-        @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
-        @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
-        @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
+            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
+            @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
+            @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
+            @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
     })
     @PostMapping("/save")
-    public R<String> save(UserEntity user)
-    {
-        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
-        {
+    public R<String> save(UserEntity user) {
+        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
             return R.fail("用户ID不能为空");
         }
         users.put(user.getUserId(), user);
@@ -81,14 +84,11 @@ public class TestController extends BaseController
 
     @ApiOperation("更新用户")
     @PutMapping("/update")
-    public R<String> update(@RequestBody UserEntity user)
-    {
-        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
-        {
+    public R<String> update(@RequestBody UserEntity user) {
+        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
             return R.fail("用户ID不能为空");
         }
-        if (users.isEmpty() || !users.containsKey(user.getUserId()))
-        {
+        if (users.isEmpty() || !users.containsKey(user.getUserId())) {
             return R.fail("用户不存在");
         }
         users.remove(user.getUserId());
@@ -99,23 +99,50 @@ public class TestController extends BaseController
     @ApiOperation("删除用户信息")
     @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
     @DeleteMapping("/{userId}")
-    public R<String> delete(@PathVariable Integer userId)
-    {
-        if (!users.isEmpty() && users.containsKey(userId))
-        {
+    public R<String> delete(@PathVariable Integer userId) {
+        if (!users.isEmpty() && users.containsKey(userId)) {
             users.remove(userId);
             return R.ok();
-        }
-        else
-        {
+        } else {
             return R.fail("用户不存在");
         }
     }
+
+
+    @ApiOperation("测试PDF上传")
+    @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
+    @PostMapping("/pdfUpload")
+    public R<String> pdfUpload(MultipartFile file) {
+        try {
+            // 上传到服务器,返回一个服务器硬盘地址
+            String upload = FileUploadUtils.uploadPdfToEs(file,"id");
+            return R.ok(upload);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return R.fail();
+
+    }
+
+    @ApiOperation("测试PDF内容搜索")
+    @ApiImplicitParam(name = "str", value = "字符串", required = true, dataTypeClass = String.class)
+    @PostMapping("/pdfData")
+    public R<List> pdfData(String str) {
+        try {
+            List<EsMessage> maps = FileUtils.eSearch(str);
+            List<String> ids = maps.stream().map(EsMessage::getId).collect(Collectors.toList());
+            return R.ok(maps);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return R.fail();
+
+    }
 }
 
+
 @ApiModel(value = "UserEntity", description = "用户实体")
-class UserEntity
-{
+class UserEntity {
     @ApiModelProperty("用户ID")
     private Integer userId;
 
@@ -128,56 +155,46 @@ class UserEntity
     @ApiModelProperty("用户手机")
     private String mobile;
 
-    public UserEntity()
-    {
+    public UserEntity() {
 
     }
 
-    public UserEntity(Integer userId, String username, String password, String mobile)
-    {
+    public UserEntity(Integer userId, String username, String password, String mobile) {
         this.userId = userId;
         this.username = username;
         this.password = password;
         this.mobile = mobile;
     }
 
-    public Integer getUserId()
-    {
+    public Integer getUserId() {
         return userId;
     }
 
-    public void setUserId(Integer userId)
-    {
+    public void setUserId(Integer userId) {
         this.userId = userId;
     }
 
-    public String getUsername()
-    {
+    public String getUsername() {
         return username;
     }
 
-    public void setUsername(String username)
-    {
+    public void setUsername(String username) {
         this.username = username;
     }
 
-    public String getPassword()
-    {
+    public String getPassword() {
         return password;
     }
 
-    public void setPassword(String password)
-    {
+    public void setPassword(String password) {
         this.password = password;
     }
 
-    public String getMobile()
-    {
+    public String getMobile() {
         return mobile;
     }
 
-    public void setMobile(String mobile)
-    {
+    public void setMobile(String mobile) {
         this.mobile = mobile;
     }
 }

+ 16 - 9
purchase-admin/src/main/resources/application.yml

@@ -10,6 +10,7 @@ purchase:
   demoEnabled: true
   # 文件路径 示例( Windows配置D:/purchase/uploadPath,Linux配置 /home/purchase/uploadPath)
   profile: C:/purchase/uploadPath
+#  profile: /Users/sunhuanhuan/Documents/project/106/文档/purchase/uploadPath
   # 获取ip地址开关
   addressEnabled: false
   # 验证码类型 math 数组计算 char 字符验证
@@ -77,8 +78,7 @@ spring:
     database: 0
     # 密码
     password: 106@qwe123
-    # 连接超时时间
-    timeout: 10s
+    # 连接超时时间    timeout: 100s
     lettuce:
       pool:
         # 连接池中的最小空闲连接
@@ -100,13 +100,13 @@ token:
     expireTime: 30
 
 # MyBatis配置
-mybatis:
-    # 搜索指定包别名
-    typeAliasesPackage: com.ozs.**.domain
-    # 配置mapper的扫描,找到所有的mapper.xml映射文件
-    mapperLocations: classpath*:mapper/**/*Mapper.xml
-    # 加载全局的配置文件
-    configLocation: classpath:mybatis/mybatis-config.xml
+#mybatis:
+#    # 搜索指定包别名
+#    typeAliasesPackage: com.ozs.**.domain
+#    # 配置mapper的扫描,找到所有的mapper.xml映射文件
+#    mapperLocations: classpath*:mapper/**/*Mapper.xml
+#    # 加载全局的配置文件
+#    configLocation: classpath:mybatis/mybatis-config.xml
 
 # MyBatis-plus配置
 mybatis-plus:
@@ -136,3 +136,10 @@ xss:
   excludes: /system/notice
   # 匹配链接
   urlPatterns: /system/*,/monitor/*,/tool/*
+
+
+elasticsearch:
+  host: 124.70.58.209
+  port: 9121
+#  host: 127.0.0.1
+#  port: 9200

+ 2 - 1
purchase-admin/src/main/resources/logback.xml

@@ -1,7 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <configuration>
     <!-- 日志存放路径 -->
-	<property name="log.path" value="/home/ruoyi/logs" />
+<!--	<property name="log.path" value="/home/ruoyi/logs" />-->
+    <property name="log.path" value="C:/purchase/logs" />
     <!-- 日志输出格式 -->
 	<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
 

+ 32 - 0
purchase-common/pom.xml

@@ -143,6 +143,38 @@
             <artifactId>mybatis-plus-boot-starter</artifactId>
         </dependency>
 
+        <!-- es  检索pdf word 内容依赖-->
+        <dependency>
+            <groupId>org.elasticsearch.client</groupId>
+            <artifactId>elasticsearch-rest-high-level-client</artifactId>
+            <version>7.13.4</version>
+        </dependency>
+        <dependency>
+            <groupId>org.elasticsearch</groupId>
+            <artifactId>elasticsearch</artifactId>
+            <version>7.13.4</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.8</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpcore</artifactId>
+            <version>4.4.9</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+            <version>1.2.7</version>
+        </dependency>
+
+        <!-- es  检索pdf word 内容依赖-->
+
         <!-- swagger3-->
         <dependency>
             <groupId>io.springfox</groupId>

+ 29 - 0
purchase-common/src/main/java/com/ozs/common/config/ElasticsearchConfig.java

@@ -0,0 +1,29 @@
+package com.ozs.common.config;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * 读取项目相关配置
+ *
+ * @author ruoyi
+ */
+@Component
+@ConfigurationProperties(prefix = "elasticsearch")
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class ElasticsearchConfig
+{
+    /** es host */
+    private String host;
+
+    /** es port */
+    private String port;
+
+
+
+}

+ 10 - 0
purchase-common/src/main/java/com/ozs/common/core/domain/BaseEntity.java

@@ -7,39 +7,49 @@ import java.util.Map;
 import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.fasterxml.jackson.annotation.JsonInclude;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
 
 /**
  * Entity基类
  *
  * @author ruoyi
  */
+@ApiModel(value = "BaseEntity", description = "基础实体")
 public class BaseEntity implements Serializable
 {
     private static final long serialVersionUID = 1L;
 
     /** 搜索值 */
     @JsonIgnore
+    @ApiModelProperty("搜索值")
     private String searchValue;
 
     /** 创建者 */
+    @ApiModelProperty("创建者")
     private String createBy;
 
     /** 创建时间 */
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    @ApiModelProperty("创建时间")
     private Date createTime;
 
     /** 更新者 */
+    @ApiModelProperty("更新者")
     private String updateBy;
 
     /** 更新时间 */
     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    @ApiModelProperty("更新时间")
     private Date updateTime;
 
     /** 备注 */
+    @ApiModelProperty("备注")
     private String remark;
 
     /** 请求参数 */
     @JsonInclude(JsonInclude.Include.NON_EMPTY)
+    @ApiModelProperty("请求参数")
     private Map<String, Object> params;
 
     public String getSearchValue()

+ 649 - 0
purchase-common/src/main/java/com/ozs/common/utils/EsUtil.java

@@ -0,0 +1,649 @@
+package com.ozs.common.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.ozs.common.config.ElasticsearchConfig;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.http.HttpHost;
+import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
+import org.elasticsearch.action.bulk.BulkRequest;
+import org.elasticsearch.action.bulk.BulkResponse;
+import org.elasticsearch.action.delete.DeleteRequest;
+import org.elasticsearch.action.delete.DeleteResponse;
+import org.elasticsearch.action.get.GetRequest;
+import org.elasticsearch.action.get.GetResponse;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.index.IndexResponse;
+import org.elasticsearch.action.search.SearchRequest;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.action.support.master.AcknowledgedResponse;
+import org.elasticsearch.action.update.UpdateRequest;
+import org.elasticsearch.action.update.UpdateResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.client.RestClient;
+import org.elasticsearch.client.RestHighLevelClient;
+import org.elasticsearch.client.indices.CreateIndexRequest;
+import org.elasticsearch.client.indices.CreateIndexResponse;
+import org.elasticsearch.client.indices.GetIndexRequest;
+import org.elasticsearch.common.text.Text;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
+import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * es 工具
+ */
+@Component
+@Slf4j
+public class EsUtil {
+
+    public static EsUtil esUtil = new EsUtil();
+
+    @Resource
+    private ElasticsearchConfig elasticsearchConfig ;
+
+    public  RestHighLevelClient client;
+
+    @PostConstruct
+    public void init() {
+        esUtil.elasticsearchConfig = this.elasticsearchConfig;
+        esUtil.client = new RestHighLevelClient(
+                RestClient.builder(
+                        new HttpHost(elasticsearchConfig.getHost(), Integer.parseInt(elasticsearchConfig.getPort()), "http")));
+    }
+
+
+
+
+    /**
+     * 停止连接
+     */
+    public static void shutdown() {
+        if (esUtil.client != null) {
+            try {
+                esUtil.client.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+
+        }
+    }
+
+    /**
+     * 默认类型(整个type类型传闻在8.0版本后可能会废弃,但是目前7.13版本下先保留)
+     */
+    public static final String DEFAULT_TYPE = "_doc";
+
+    /**
+     * set方法前缀
+     */
+    public static final String SET_METHOD_PREFIX = "set";
+
+    /**
+     * 返回状态-CREATED
+     */
+    public static final String RESPONSE_STATUS_CREATED = "CREATED";
+
+    /**
+     * 返回状态-OK
+     */
+    public static final String RESPONSE_STATUS_OK = "OK";
+
+    /**
+     * 返回状态-NOT_FOUND
+     */
+    public static final String RESPONSE_STATUS_NOT_FOUND = "NOT_FOUND";
+
+    /**
+     * 需要过滤的文档数据
+     */
+    public static final String[] IGNORE_KEY = {"@timestamp", "@version", "type"};
+
+    /**
+     * 超时时间 1s
+     */
+    public static final TimeValue TIME_VALUE_SECONDS = TimeValue.timeValueSeconds(1);
+
+    /**
+     * 批量新增
+     */
+    public static final String PATCH_OP_TYPE_INSERT = "insert";
+
+    /**
+     * 批量删除
+     */
+    public static final String PATCH_OP_TYPE_DELETE = "delete";
+
+    /**
+     * 批量更新
+     */
+    public static final String PATCH_OP_TYPE_UPDATE = "update";
+
+//==========================================数据操作(工具)(不参与调用es)=================================================
+
+    /**
+     * 方法描述: 剔除指定文档数据,减少不必要的循环
+     *
+     * @param map 文档数据
+     * @return: void
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:39 上午
+     */
+    public static void ignoreSource(Map<String, Object> map) {
+        for (String key : IGNORE_KEY) {
+            map.remove(key);
+        }
+    }
+
+
+    /**
+     * 方法描述: 将文档数据转化为指定对象
+     *
+     * @param sourceAsMap 文档数据
+     * @param clazz       转换目标Class对象
+     * @return 对象
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:38 上午
+     */
+    public static <T> T dealObject(Map<String, Object> sourceAsMap, Class<T> clazz) {
+        try {
+            ignoreSource(sourceAsMap);
+            Iterator<String> keyIterator = sourceAsMap.keySet().iterator();
+            T t = clazz.newInstance();
+            while (keyIterator.hasNext()) {
+                String key = keyIterator.next();
+                String replaceKey = key.replaceFirst(key.substring(0, 1), key.substring(0, 1).toUpperCase());
+                Method method = null;
+                try {
+                    method = clazz.getMethod(SET_METHOD_PREFIX + replaceKey, sourceAsMap.get(key).getClass());
+                } catch (NoSuchMethodException e) {
+                    continue;
+                }
+                method.invoke(t, sourceAsMap.get(key));
+            }
+            return t;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+//==========================================索引操作=================================================
+
+    /**
+     * 方法描述: 创建索引,若索引不存在且创建成功,返回true,若同名索引已存在,返回false
+     *
+     * @param: [index] 索引名称
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 11:01 上午
+     */
+    public static boolean insertIndex(String index) {
+        //创建索引请求
+        CreateIndexRequest request = new CreateIndexRequest(index);
+        //执行创建请求IndicesClient,请求后获得响应
+        try {
+            CreateIndexResponse response = esUtil.client.indices().create(request, RequestOptions.DEFAULT);
+            return response != null;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+    /**
+     * 方法描述: 判断索引是否存在,若存在返回true,若不存在或出现问题返回false
+     *
+     * @param: [index] 索引名称
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 11:09 上午
+     */
+    public static boolean isExitsIndex(String index) {
+        GetIndexRequest request = new GetIndexRequest(index);
+        try {
+            return esUtil.client.indices().exists(request, RequestOptions.DEFAULT);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+    /*
+     * 方法描述: 删除索引,删除成功返回true,删除失败返回false
+     * @param: [index] 索引名称
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 11:23 上午
+     */
+    public static boolean deleteIndex(String index) {
+        DeleteIndexRequest request = new DeleteIndexRequest(index);
+        try {
+            AcknowledgedResponse response = esUtil.client.indices().delete(request, RequestOptions.DEFAULT);
+            return response.isAcknowledged();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+//==========================================文档操作(新增,删除,修改)=================================================
+
+    /**
+     * 方法描述: 新增/修改文档信息
+     *
+     * @param index 索引
+     * @param id    文档id
+     * @param data  数据
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:34 上午
+     */
+    public static boolean insertOrUpdateDocument(String index, String id, Object data) {
+        try {
+            IndexRequest request = new IndexRequest(index);
+            request.timeout(TIME_VALUE_SECONDS);
+            if (id != null && id.length() > 0) {
+                request.id(id);
+            }
+            request.source(JSON.toJSONString(data), XContentType.JSON);
+            IndexResponse response = esUtil.client.index(request, RequestOptions.DEFAULT);
+            String status = response.status().toString();
+            if (RESPONSE_STATUS_CREATED.equals(status) || RESPONSE_STATUS_OK.equals(status)) {
+                return true;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    /**
+     * 方法描述: 更新文档信息
+     *
+     * @param index 索引
+     * @param id    文档id
+     * @param data  数据
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:34 上午
+     */
+    public static boolean updateDocument(String index, String id, Object data) {
+        try {
+            UpdateRequest request = new UpdateRequest(index, id);
+            request.doc(JSON.toJSONString(data), XContentType.JSON);
+            UpdateResponse response = esUtil.client.update(request, RequestOptions.DEFAULT);
+            String status = response.status().toString();
+            if (RESPONSE_STATUS_OK.equals(status)) {
+                return true;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    /**
+     * 方法描述:删除文档信息
+     *
+     * @param index 索引
+     * @param id    文档id
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:33 上午
+     */
+    public static boolean deleteDocument(String index, String id) {
+        try {
+            DeleteRequest request = new DeleteRequest(index, id);
+            DeleteResponse response = esUtil.client.delete(request, RequestOptions.DEFAULT);
+            String status = response.status().toString();
+            if (RESPONSE_STATUS_OK.equals(status)) {
+                return true;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+    /**
+     * 方法描述: 小数据量批量新增
+     *
+     * @param index    索引
+     * @param dataList 数据集 新增修改需要传递
+     * @param timeout  超时时间 单位为秒
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:31 上午
+     */
+    public static boolean simplePatchInsert(String index, List<Object> dataList, long timeout) {
+        try {
+            BulkRequest bulkRequest = new BulkRequest();
+            bulkRequest.timeout(TimeValue.timeValueSeconds(timeout));
+            if (dataList != null && dataList.size() > 0) {
+                for (Object obj : dataList) {
+                    bulkRequest.add(
+                            new IndexRequest(index)
+                                    .source(JSON.toJSONString(obj), XContentType.JSON)
+                    );
+                }
+                BulkResponse response = esUtil.client.bulk(bulkRequest, RequestOptions.DEFAULT);
+                if (!response.hasFailures()) {
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+    /**
+     * 功能描述:
+     * @param index 索引名称
+     * @param idList 需要批量删除的id集合
+     * @return : boolean
+     * @author : gxf
+     * @date : 2021/6/30 1:22
+     */
+    public static boolean patchDelete(String index, List<String> idList) {
+        BulkRequest request = new BulkRequest();
+        for (String id:idList) {
+            request.add(new DeleteRequest().index(index).id(id));
+        }
+        try {
+            BulkResponse response = EsUtil.esUtil.client.bulk(request, RequestOptions.DEFAULT);
+            return !response.hasFailures();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+//==========================================文档操作(查询)=================================================
+
+    /**
+     * 方法描述: 判断文档是否存在
+     *
+     * @param index 索引
+     * @param id    文档id
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:36 上午
+     */
+    public static boolean isExistsDocument(String index, String id) {
+        return isExistsDocument(index, DEFAULT_TYPE, id);
+    }
+
+
+    /**
+     * 方法描述: 判断文档是否存在
+     *
+     * @param index 索引
+     * @param type  类型
+     * @param id    文档id
+     * @return: boolean
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:36 上午
+     */
+    public static boolean isExistsDocument(String index, String type, String id) {
+        GetRequest request = new GetRequest(index, type, id);
+        try {
+            GetResponse response = esUtil.client.get(request, RequestOptions.DEFAULT);
+            return response.isExists();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return false;
+    }
+
+
+    /**
+     * 方法描述: 根据id查询文档
+     *
+     * @param index 索引
+     * @param id    文档id
+     * @param clazz 转换目标Class对象
+     * @return 对象
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:36 上午
+     */
+    public static <T> T selectDocumentById(String index, String id, Class<T> clazz) {
+        return selectDocumentById(index, DEFAULT_TYPE, id, clazz);
+    }
+
+
+    /**
+     * 方法描述: 根据id查询文档
+     *
+     * @param index 索引
+     * @param type  类型
+     * @param id    文档id
+     * @param clazz 转换目标Class对象
+     * @return 对象
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:35 上午
+     */
+    public static <T> T selectDocumentById(String index, String type, String id, Class<T> clazz) {
+        try {
+            type = type == null || type.equals("") ? DEFAULT_TYPE : type;
+            GetRequest request = new GetRequest(index, type, id);
+            GetResponse response = esUtil.client.get(request, RequestOptions.DEFAULT);
+            if (response.isExists()) {
+                Map<String, Object> sourceAsMap = response.getSourceAsMap();
+                return dealObject(sourceAsMap, clazz);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 方法描述:(筛选条件)获取数据集合
+     *
+     * @param index         索引
+     * @param sourceBuilder 请求条件
+     * @param clazz         转换目标Class对象
+     * @return: java.util.List<T>
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:35 上午
+     */
+    public static <T> List<T> selectDocumentList(String index, SearchSourceBuilder sourceBuilder, Class<T> clazz) {
+        try {
+            SearchRequest request = new SearchRequest(index);
+            if (sourceBuilder != null) {
+                // 返回实际命中数
+                sourceBuilder.trackTotalHits(true);
+                request.source(sourceBuilder);
+            }
+            SearchResponse response = esUtil.client.search(request, RequestOptions.DEFAULT);
+            if (response.getHits() != null) {
+                List<T> list = new ArrayList<>();
+                SearchHit[] hits = response.getHits().getHits();
+                for (SearchHit documentFields : hits) {
+                    Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
+                    list.add(dealObject(sourceAsMap, clazz));
+                }
+                return list;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 方法描述:(筛选条件)获取数据
+     *
+     * @param index         索引
+     * @param sourceBuilder 请求条
+     * @return: java.util.List<T>
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 10:35 上午
+     */
+    public static SearchResponse selectDocument(String index, SearchSourceBuilder sourceBuilder) {
+        try {
+            SearchRequest request = new SearchRequest(index);
+            if (sourceBuilder != null) {
+                // 返回实际命中数
+                sourceBuilder.trackTotalHits(true);
+                sourceBuilder.size(10000);
+                request.source(sourceBuilder);
+            }
+            return esUtil.client.search(request, RequestOptions.DEFAULT);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 方法描述: 筛选查询,返回使用了<span style='color:red'></span>处理好的数据.
+     *
+     * @param: index 索引名称
+     * @param: sourceBuilder sourceBuilder对象
+     * @param: clazz 需要返回的对象类型.class
+     * @param: highLight 需要表现的高亮匹配字段
+     * @return: java.util.List<T>
+     * @author: gxf
+     * @date: 2021年07月27日
+     * @time: 6:39 下午
+     */
+    public static <T> List<T> selectDocumentListHighLight(String index, SearchSourceBuilder sourceBuilder, Class<T> clazz, String highLight) {
+        try {
+            SearchRequest request = new SearchRequest(index);
+            if (sourceBuilder != null) {
+                // 返回实际命中数
+                sourceBuilder.trackTotalHits(true);
+                //高亮
+                HighlightBuilder highlightBuilder = new HighlightBuilder();
+                highlightBuilder.field(highLight);
+                highlightBuilder.requireFieldMatch(false);//多个高亮关闭
+                highlightBuilder.preTags("<span style='color:red'>");
+                highlightBuilder.postTags("</span>");
+                sourceBuilder.highlighter(highlightBuilder);
+                request.source(sourceBuilder);
+            }
+            SearchResponse response = esUtil.client.search(request, RequestOptions.DEFAULT);
+            if (response.getHits() != null) {
+                List<T> list = new ArrayList<>();
+                for (SearchHit documentFields : response.getHits().getHits()) {
+                    Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
+                    HighlightField title = highlightFields.get(highLight);
+                    Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
+                    if (title != null) {
+                        Text[] fragments = title.fragments();
+                        String n_title = "";
+                        for (Text fragment : fragments) {
+                            n_title += fragment;
+                        }
+                        sourceAsMap.put(highLight, n_title);//高亮替换原来的内容
+                    }
+                    list.add(dealObject(sourceAsMap, clazz));
+                }
+                return list;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 方法描述: 返回索引内所有内容,返回SearchResponse对象,需要自己解析,不对数据封装
+     * @param: index 索引名称
+     * @return: SearchResponse
+     * @author: gxf
+     * @date: 2021/6/30
+     * @time: 1:28 上午
+     */
+    public static SearchResponse queryAllData(String index){
+        //创建搜索请求对象
+        SearchRequest request = new SearchRequest(index);
+        //构建查询的请求体
+        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
+        //查询所有数据
+        sourceBuilder.query(QueryBuilders.matchAllQuery());
+        request.source(sourceBuilder);
+        try {
+            return esUtil.client.search(request, RequestOptions.DEFAULT);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
+    /**
+     * 方法描述: 返回索引内所有内容,返回指定类型
+     * @param: index 索引名称
+     * @param: clazz 需要接受转换的对象类型
+     * @return: java.util.List<T>
+     * @author: gxf
+     * @date: 2021/6/30
+     * @time: 1:32 上午
+     */
+    public static <T> List<T> queryAllData(String index, Class<T> clazz){
+        //创建搜索请求对象
+        SearchRequest request = new SearchRequest(index);
+        //构建查询的请求体
+        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
+        //查询所有数据
+        sourceBuilder.query(QueryBuilders.matchAllQuery());
+        request.source(sourceBuilder);
+        try {
+            SearchResponse response = esUtil.client.search(request, RequestOptions.DEFAULT);
+            if (response.getHits() != null) {
+                List<T> list = new ArrayList<>();
+                SearchHit[] hits = response.getHits().getHits();
+                for (SearchHit documentFields : hits) {
+                    Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
+                    list.add(dealObject(sourceAsMap, clazz));
+                }
+                return list;
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+}
+

+ 70 - 0
purchase-common/src/main/java/com/ozs/common/utils/file/FileUploadUtils.java

@@ -146,6 +146,7 @@ public class FileUploadUtils
         int dirLastIndex = PurchaseConfig.getProfile().length() + 1;
         String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
         return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
+//        return uploadDir + "/"+ fileName;
     }
 
     /**
@@ -230,4 +231,73 @@ public class FileUploadUtils
         }
         return extension;
     }
+
+    /**
+     * 上次文件内容到es
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    public static final String uploadPdfToEs(MultipartFile file,String id) throws IOException
+    {
+        try
+        {
+            return uploadPdfToEs(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION,id);
+        }
+        catch (Exception e)
+        {
+            throw new IOException(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * 文件上传
+     *
+     * @param baseDir 相对应用的基目录
+     * @param file 上传的文件
+     * @param allowedExtension 上传文件类型
+     * @return 返回上传成功的文件名
+     * @throws FileSizeLimitExceededException 如果超出最大大小
+     * @throws FileNameLengthLimitExceededException 文件名太长
+     * @throws IOException 比如读写文件出错时
+     * @throws InvalidExtensionException 文件校验异常
+     */
+    public static final String uploadPdfToEs(String baseDir, MultipartFile file, String[] allowedExtension,String id)
+            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
+            InvalidExtensionException
+    {
+        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
+        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
+        {
+            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
+        }
+
+        assertAllowed(file, allowedExtension);
+
+        String fileName = extractEsFilename(file);
+
+        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
+        file.transferTo(Paths.get(absPath));
+        String pathName = getPathName(baseDir, fileName);
+        // 上传文件内容到es
+        FileUtils.uploadESFile(pathName,id);
+
+        return pathName;
+    }
+
+    public static final String getPathName(String uploadDir, String fileName) throws IOException
+    {
+        int dirLastIndex = PurchaseConfig.getProfile().length() + 1;
+        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
+        return uploadDir + "/"+ fileName;
+    }
+
+    /**
+     * 编码文件名
+     */
+    public static final String extractEsFilename(MultipartFile file)
+    {
+        return StringUtils.format("{}/{}.{}", DateUtils.datePath(),
+                FilenameUtils.getBaseName(file.getOriginalFilename()), getExtension(file));
+    }
 }

+ 148 - 79
purchase-common/src/main/java/com/ozs/common/utils/file/FileUtils.java

@@ -8,58 +8,73 @@ import java.io.IOException;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
+import java.net.UnknownHostException;
 import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import com.alibaba.fastjson2.JSON;
+import com.ozs.common.utils.EsUtil;
 import com.ozs.common.utils.StringUtils;
+import com.ozs.common.vo.EsMessage;
+import com.ozs.common.vo.FileMessage;
+import jdk.internal.org.xml.sax.SAXException;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.ArrayUtils;
 import com.ozs.common.config.PurchaseConfig;
 import com.ozs.common.utils.DateUtils;
 import com.ozs.common.utils.uuid.IdUtils;
 import org.apache.commons.io.FilenameUtils;
+import org.elasticsearch.action.index.IndexRequest;
+import org.elasticsearch.action.index.IndexResponse;
+import org.elasticsearch.action.search.SearchResponse;
+import org.elasticsearch.client.RequestOptions;
+import org.elasticsearch.common.xcontent.XContentType;
+import org.elasticsearch.index.query.QueryBuilders;
+import org.elasticsearch.search.SearchHit;
+import org.elasticsearch.search.SearchHits;
+import org.elasticsearch.search.builder.SearchSourceBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * 文件处理工具类
  *
  * @author ruoyi
  */
-public class FileUtils
-{
+@Slf4j
+public class FileUtils {
+
     public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
 
     /**
      * 输出指定文件的byte数组
      *
      * @param filePath 文件路径
-     * @param os 输出流
+     * @param os       输出流
      * @return
      */
-    public static void writeBytes(String filePath, OutputStream os) throws IOException
-    {
+    public static void writeBytes(String filePath, OutputStream os) throws IOException {
         FileInputStream fis = null;
-        try
-        {
+        try {
             File file = new File(filePath);
-            if (!file.exists())
-            {
+            if (!file.exists()) {
                 throw new FileNotFoundException(filePath);
             }
             fis = new FileInputStream(file);
             byte[] b = new byte[1024];
             int length;
-            while ((length = fis.read(b)) > 0)
-            {
+            while ((length = fis.read(b)) > 0) {
                 os.write(b, 0, length);
             }
-        }
-        catch (IOException e)
-        {
+        } catch (IOException e) {
             throw e;
-        }
-        finally
-        {
+        } finally {
             IOUtils.close(os);
             IOUtils.close(fis);
         }
@@ -72,33 +87,28 @@ public class FileUtils
      * @return 目标文件
      * @throws IOException IO异常
      */
-    public static String writeImportBytes(byte[] data) throws IOException
-    {
+    public static String writeImportBytes(byte[] data) throws IOException {
         return writeBytes(data, PurchaseConfig.getImportPath());
     }
 
     /**
      * 写数据到文件中
      *
-     * @param data 数据
+     * @param data      数据
      * @param uploadDir 目标文件
      * @return 目标文件
      * @throws IOException IO异常
      */
-    public static String writeBytes(byte[] data, String uploadDir) throws IOException
-    {
+    public static String writeBytes(byte[] data, String uploadDir) throws IOException {
         FileOutputStream fos = null;
         String pathName = "";
-        try
-        {
+        try {
             String extension = getFileExtendName(data);
             pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
             File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
             fos = new FileOutputStream(file);
             fos.write(data);
-        }
-        finally
-        {
+        } finally {
             IOUtils.close(fos);
         }
         return FileUploadUtils.getPathFileName(uploadDir, pathName);
@@ -110,13 +120,11 @@ public class FileUtils
      * @param filePath 文件
      * @return
      */
-    public static boolean deleteFile(String filePath)
-    {
+    public static boolean deleteFile(String filePath) {
         boolean flag = false;
         File file = new File(filePath);
         // 路径为文件且不为空则进行删除
-        if (file.isFile() && file.exists())
-        {
+        if (file.isFile() && file.exists()) {
             flag = file.delete();
         }
         return flag;
@@ -128,8 +136,7 @@ public class FileUtils
      * @param filename 文件名称
      * @return true 正常 false 非法
      */
-    public static boolean isValidFilename(String filename)
-    {
+    public static boolean isValidFilename(String filename) {
         return filename.matches(FILENAME_PATTERN);
     }
 
@@ -139,17 +146,14 @@ public class FileUtils
      * @param resource 需要下载的文件
      * @return true 正常 false 非法
      */
-    public static boolean checkAllowDownload(String resource)
-    {
+    public static boolean checkAllowDownload(String resource) {
         // 禁止目录上跳级别
-        if (StringUtils.contains(resource, ".."))
-        {
+        if (StringUtils.contains(resource, "..")) {
             return false;
         }
 
         // 检查允许下载的文件规则
-        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
-        {
+        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
             return true;
         }
 
@@ -160,32 +164,24 @@ public class FileUtils
     /**
      * 下载文件名重新编码
      *
-     * @param request 请求对象
+     * @param request  请求对象
      * @param fileName 文件名
      * @return 编码后的文件名
      */
-    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
-    {
+    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
         final String agent = request.getHeader("USER-AGENT");
         String filename = fileName;
-        if (agent.contains("MSIE"))
-        {
+        if (agent.contains("MSIE")) {
             // IE浏览器
             filename = URLEncoder.encode(filename, "utf-8");
             filename = filename.replace("+", " ");
-        }
-        else if (agent.contains("Firefox"))
-        {
+        } else if (agent.contains("Firefox")) {
             // 火狐浏览器
             filename = new String(fileName.getBytes(), "ISO8859-1");
-        }
-        else if (agent.contains("Chrome"))
-        {
+        } else if (agent.contains("Chrome")) {
             // google浏览器
             filename = URLEncoder.encode(filename, "utf-8");
-        }
-        else
-        {
+        } else {
             // 其它浏览器
             filename = URLEncoder.encode(filename, "utf-8");
         }
@@ -195,11 +191,10 @@ public class FileUtils
     /**
      * 下载文件名重新编码
      *
-     * @param response 响应对象
+     * @param response     响应对象
      * @param realFileName 真实文件名
      */
-    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
-    {
+    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
         String percentEncodedFileName = percentEncode(realFileName);
 
         StringBuilder contentDispositionValue = new StringBuilder();
@@ -221,8 +216,7 @@ public class FileUtils
      * @param s 需要百分号编码的字符串
      * @return 百分号编码后的字符串
      */
-    public static String percentEncode(String s) throws UnsupportedEncodingException
-    {
+    public static String percentEncode(String s) throws UnsupportedEncodingException {
         String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
         return encode.replaceAll("\\+", "%20");
     }
@@ -233,24 +227,16 @@ public class FileUtils
      * @param photoByte 图像数据
      * @return 后缀名
      */
-    public static String getFileExtendName(byte[] photoByte)
-    {
+    public static String getFileExtendName(byte[] photoByte) {
         String strFileExtendName = "jpg";
         if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
-                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
-        {
+                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
             strFileExtendName = "gif";
-        }
-        else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
-        {
+        } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
             strFileExtendName = "jpg";
-        }
-        else if ((photoByte[0] == 66) && (photoByte[1] == 77))
-        {
+        } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
             strFileExtendName = "bmp";
-        }
-        else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
-        {
+        } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
             strFileExtendName = "png";
         }
         return strFileExtendName;
@@ -262,10 +248,8 @@ public class FileUtils
      * @param fileName 路径名称
      * @return 没有文件路径的名称
      */
-    public static String getName(String fileName)
-    {
-        if (fileName == null)
-        {
+    public static String getName(String fileName) {
+        if (fileName == null) {
             return null;
         }
         int lastUnixPos = fileName.lastIndexOf('/');
@@ -280,13 +264,98 @@ public class FileUtils
      * @param fileName 路径名称
      * @return 没有文件路径和后缀的名称
      */
-    public static String getNameNotSuffix(String fileName)
-    {
-        if (fileName == null)
-        {
+    public static String getNameNotSuffix(String fileName) {
+        if (fileName == null) {
             return null;
         }
         String baseName = FilenameUtils.getBaseName(fileName);
         return baseName;
     }
+
+
+    /**
+     * 上传文档到es
+     * @param filePath
+     * @param id  当前文件入库id
+     */
+    public static void uploadESFile(String filePath,String id) {
+        File file = new File(filePath);
+        if (!file.exists()) {
+            System.out.println("找不到文件");
+        }
+        FileMessage fileM = new FileMessage();
+        try {
+            byte[] bytes = getContent(file);
+            String base64 = Base64.getEncoder().encodeToString(bytes);
+            fileM.setId(id);
+            fileM.setName(file.getName());
+            fileM.setContent(base64);
+            IndexRequest indexRequest = new IndexRequest("fileindex");
+            //上传同时,使用attachment pipline进行提取文件
+            indexRequest.source(JSON.toJSONString(fileM), XContentType.JSON);
+            indexRequest.setPipeline("attachment");
+            IndexResponse indexResponse = EsUtil.esUtil.client.index(indexRequest, RequestOptions.DEFAULT);
+            log.info("send to eSearch:" + fileM.getName());
+            log.info("send to eSeach results:" + indexResponse);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 文件转base64
+     *
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    public static byte[] getContent(File file) throws IOException {
+
+        long fileSize = file.length();
+        if (fileSize > Integer.MAX_VALUE) {
+            System.out.println("file too big...");
+            return null;
+        }
+        FileInputStream fi = new FileInputStream(file);
+        byte[] buffer = new byte[(int) fileSize];
+        int offset = 0;
+        int numRead = 0;
+        while (offset < buffer.length
+                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
+            offset += numRead;
+        }
+        // 确保所有数据均被读取
+        if (offset != buffer.length) {
+            throw new IOException("Could not completely read file "
+                    + file.getName());
+        }
+        fi.close();
+        return buffer;
+    }
+
+
+    public static List<EsMessage> eSearch(String msg) throws UnknownHostException {
+//
+        List<EsMessage> matchRsult = new LinkedList<EsMessage>();
+        SearchSourceBuilder builder = new SearchSourceBuilder();
+
+        //因为我这边实际业务需要其他字段的查询,所以进行查询的字段就比较,如果只是查询文档中内容的话,打开注释的代码,然后注释掉这行代码
+        builder.query(QueryBuilders.multiMatchQuery(msg, "attachment.content", "name", "sfName", "createBy").analyzer("ik_smart"));
+
+        //builder.query(QueryBuilders.matchQuery("attachment.content", msg).analyzer("ik_smart"));
+        SearchResponse searchResponse = EsUtil.selectDocument("fileindex", builder);
+        SearchHits hits = searchResponse.getHits();
+
+        for (SearchHit hit : hits.getHits()) {
+            hit.getSourceAsMap().put("msg", "");
+            matchRsult.add(JSON.parseObject(JSON.toJSONString(hit.getSourceAsMap()),EsMessage.class));
+            // System.out.println(hit.getSourceAsString());
+        }
+        System.out.println("over in the main");
+
+        return matchRsult;
+    }
+
+
 }

+ 21 - 0
purchase-common/src/main/java/com/ozs/common/vo/Attachment.java

@@ -0,0 +1,21 @@
+package com.ozs.common.vo;
+
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.util.Date;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class Attachment {
+    private Date  date;
+    private String content_type;
+    private String title;
+    private String content;
+    private Long content_length;
+}

+ 19 - 0
purchase-common/src/main/java/com/ozs/common/vo/EsMessage.java

@@ -0,0 +1,19 @@
+package com.ozs.common.vo;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class EsMessage {
+
+    private String msg; //用于存储文件id
+    private Attachment attachment; //文件名
+    private String name; //文件的type,pdf,word,or txt
+    private String id; //文件转化成base64编码后所有的内容。
+
+}

+ 19 - 0
purchase-common/src/main/java/com/ozs/common/vo/FileMessage.java

@@ -0,0 +1,19 @@
+package com.ozs.common.vo;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+@Builder
+public class FileMessage {
+
+    private String id; //用于存储文件id
+    private String name; //文件名
+    private String type; //文件的type,pdf,word,or txt
+    private String content; //文件转化成base64编码后所有的内容。
+
+}

+ 19 - 0
purchase-system/src/main/java/com/ozs/base/domain/BaseSupplier.java

@@ -0,0 +1,19 @@
+package com.ozs.base.domain;
+
+import lombok.Data;
+
+/**
+ * 供应商管理
+ *
+ * @author sunhh
+ */
+@Data
+public class BaseSupplier {
+    private int id;
+    private String supplierName;
+    private String supplierResponsiblePerson;
+    private String supplierAddress;
+    private String supplierType;
+    private String supplierState;
+    private String supplierAdvancePurchase;
+}

+ 21 - 0
purchase-system/src/main/java/com/ozs/base/mapper/BaseSupplierMapper.java

@@ -0,0 +1,21 @@
+package com.ozs.base.mapper;
+
+import com.ozs.base.domain.BaseSupplier;
+import org.apache.ibatis.annotations.Mapper;
+
+/**
+ * 供应商管理
+ *
+ * @author sunhh
+ */
+@Mapper
+public interface BaseSupplierMapper {
+
+    /**
+     * 新增参数配置
+     *
+     * @param baseSupplier 参数配置信息
+     * @return 结果
+     */
+    public int insertBaseSupplier(BaseSupplier baseSupplier);
+}

+ 20 - 0
purchase-system/src/main/java/com/ozs/base/service/BaseSupplierService.java

@@ -0,0 +1,20 @@
+package com.ozs.base.service;
+
+import com.ozs.base.domain.BaseSupplier;
+
+/**
+ * 供应商管理
+ *
+ * @author sunhh
+ */
+public interface BaseSupplierService {
+
+    /**
+     * 新增供应商
+     *
+     * @param baseSupplier 供应商信息
+     * @return 结果
+     */
+    public int insertBaseSupplier(BaseSupplier baseSupplier);
+
+}

+ 24 - 0
purchase-system/src/main/java/com/ozs/base/service/impl/BaseSupplierServiceImpl.java

@@ -0,0 +1,24 @@
+package com.ozs.base.service.impl;
+
+import com.ozs.base.domain.BaseSupplier;
+import com.ozs.base.mapper.BaseSupplierMapper;
+import com.ozs.base.service.BaseSupplierService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+/**
+ * 供应商管理
+ *
+ * @author sunhh
+ */
+@Service
+public class BaseSupplierServiceImpl implements BaseSupplierService {
+
+    @Autowired
+    private BaseSupplierMapper baseSupplierMapper;
+
+    @Override
+    public int insertBaseSupplier(BaseSupplier baseSupplier) {
+        return baseSupplierMapper.insertBaseSupplier(baseSupplier);
+    }
+}

+ 9 - 0
purchase-system/src/main/java/com/ozs/system/domain/SysConfig.java

@@ -2,6 +2,9 @@ package com.ozs.system.domain;
 
 import javax.validation.constraints.NotBlank;
 import javax.validation.constraints.Size;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
 import org.apache.commons.lang3.builder.ToStringBuilder;
 import org.apache.commons.lang3.builder.ToStringStyle;
 import com.ozs.common.annotation.Excel;
@@ -13,28 +16,34 @@ import com.ozs.common.core.domain.BaseEntity;
  *
  * @author ruoyi
  */
+@ApiModel(value = "SysConfig", description = "参数配置")
 public class SysConfig extends BaseEntity
 {
     private static final long serialVersionUID = 1L;
 
     /** 参数主键 */
     @Excel(name = "参数主键", cellType = ColumnType.NUMERIC)
+    @ApiModelProperty("参数主键")
     private Long configId;
 
     /** 参数名称 */
     @Excel(name = "参数名称")
+    @ApiModelProperty("参数名称")
     private String configName;
 
     /** 参数键名 */
     @Excel(name = "参数键名")
+    @ApiModelProperty("参数键名")
     private String configKey;
 
     /** 参数键值 */
     @Excel(name = "参数键值")
+    @ApiModelProperty("参数键值")
     private String configValue;
 
     /** 系统内置(Y是 N否) */
     @Excel(name = "系统内置", readConverterExp = "Y=是,N=否")
+    @ApiModelProperty("系统内置")
     private String configType;
 
     public Long getConfigId()

+ 27 - 0
purchase-system/src/main/resources/mapper/base/BaseSupplierMapper.xml

@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper
+        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.ozs.base.mapper.BaseSupplierMapper">
+
+    <insert id="insertBaseSupplier" parameterType="BaseSupplier">
+        insert into base_supplier (
+        <if test="supplierName != null and supplierName != '' ">supplier_name,</if>
+        <if test="supplierResponsiblePerson != null and supplierResponsiblePerson != '' ">supplier_responsible_person,
+        </if>
+        <if test="supplierAddress != null and supplierAddress != '' ">supplier_address,</if>
+        <if test="supplierType != null and supplierType != '' ">supplier_type,</if>
+        <if test="supplierState != null and supplierState != ''">supplier_state,</if>
+        <if test="supplierAdvancePurchase != null and supplierAdvancePurchase != ''">supplier_advance_purchase,</if>
+        ) values (
+        <if test="supplierName != null and supplierName != ''">#{supplierName},</if>
+        <if test="supplierResponsiblePerson != null and supplierResponsiblePerson != ''">#{supplierResponsiblePerson},
+        </if>
+        <if test="supplierAddress != null and supplierAddress != ''">#{supplierAddress},</if>
+        <if test="supplierType != null and supplierType != ''">#{supplierType},</if>
+        <if test="supplierState != null and supplierState != ''">#{supplierState},</if>
+        <if test="supplierAdvancePurchase != null and supplierAdvancePurchase != ''">#{supplierAdvancePurchase},</if>
+        )
+    </insert>
+
+</mapper>