Browse Source

添加BMS故障码

bridge 1 year ago
parent
commit
fded8613e6

+ 6 - 6
pom.xml

@@ -48,6 +48,12 @@
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>easyexcel</artifactId>
+            <version>3.3.1</version>
+        </dependency>
+
         <dependency>
             <groupId>com.squareup.okhttp3</groupId>
             <artifactId>okhttp</artifactId>
@@ -137,12 +143,6 @@
             <version>1.13</version>
         </dependency>
 
-        <dependency>
-            <groupId>org.apache.poi</groupId>
-            <artifactId>poi</artifactId>
-            <version>4.1.0</version>
-        </dependency>
-
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-configuration-processor</artifactId>

+ 97 - 0
src/main/java/cn/fastfun/controller/api/AlarmCodeController.java

@@ -0,0 +1,97 @@
+package cn.fastfun.controller.api;
+
+import cn.fastfun.controller.param.LoginParam;
+import cn.fastfun.service.AlarmService;
+import cn.fastfun.service.UtilService;
+import cn.fastfun.service.entity.AlarmCode;
+import cn.fastfun.service.entity.SysUser;
+import cn.fastfun.util.FileUtils;
+import com.alibaba.excel.EasyExcel;
+import com.bridge.dto.*;
+import com.bridge.service.JpaService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.DigestUtils;
+import org.springframework.util.ObjectUtils;
+import org.springframework.util.StringUtils;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+@Api(tags = {"4.0 故障字典"})
+@RestController
+@RequestMapping("/api/v1/alarm/code")
+public class AlarmCodeController {
+
+    @Autowired
+    UtilService utilService;
+
+    @Resource(name = "alarmCodeService")
+    JpaService<AlarmCode, String> alarmCodeService;
+
+    @Resource
+    AlarmService alarmService;
+
+    @ApiOperation(value = "导入Excel")
+    @PostMapping("/excel/upload")
+    public ApiDTO upload(MultipartFile file, String protocolCode) {
+        if (ObjectUtils.isEmpty(protocolCode) || "undefined".equals(protocolCode)) {
+            return ApiDTO.error("协议不能为空");
+        }
+        String filePath = alarmService.uploadFile(file);
+        List<String> ids = alarmCodeService.findAll(QueryParamExp.eq("protocolCode", protocolCode)).stream().map(p -> p.getId()).collect(Collectors.toList());
+        if (!CollectionUtils.isEmpty(ids)) {
+            alarmCodeService.delete(ids);
+        }
+        List<Map<Integer, String>> listMap = EasyExcel.read(alarmService.getPath().concat(filePath)).sheet().headRowNumber(1).doReadSync();
+        String title = "";
+        List<AlarmCode> list = new ArrayList<>();
+        for (Map<Integer, String> m : listMap) {
+            if (ObjectUtils.isEmpty(m.get(0))) {
+                m.put(0, title);
+            } else {
+                title = m.get(0);
+            }
+            AlarmCode p = new AlarmCode(m);
+            p.setProtocolCode(protocolCode);
+            p.setFileUrl(filePath);
+            list.add(p);
+        }
+        if (!CollectionUtils.isEmpty(list)) {
+            alarmCodeService.save(list);
+        }
+        return ApiDTO.ok();
+    }
+
+    /**
+     * 数据保存
+     */
+    @ApiOperation(value = "文件流")
+    @GetMapping(value = "excel/{protocol}")
+    public ApiDTO save(@PathVariable String protocol, HttpServletResponse response) {
+        List<AlarmCode> list = alarmCodeService.findAll(QueryParamExp.eq("protocolCode", protocol));
+        File file = new File(alarmService.getPath().concat(list.get(0).getFileUrl()));
+        FileUtils.outFile(response, list.get(0).getFileUrl(), file);
+        return ApiDTO.ok("保存成功");
+    }
+
+    @ApiOperation(value = "分页搜索")
+    @RequestMapping(value = "pageQuery", method = RequestMethod.POST)
+    public ApiPageDTO pageQuery(@RequestBody QueryParam param) {
+        param.addGroup("protocolCode");
+        return new ApiPageDTO(null, alarmCodeService.findByParam(param));
+    }
+}

+ 58 - 0
src/main/java/cn/fastfun/service/AlarmService.java

@@ -0,0 +1,58 @@
+package cn.fastfun.service;
+
+import com.bridge.exception.ApiRuntimeException;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.UUID;
+
+/**
+ * @author bridge
+ * @date 2023/8/8  14:06
+ */
+@Slf4j
+@Service
+public class AlarmService {
+
+    @Autowired
+    Environment environment;
+
+    public String getPath() {
+        return environment.getProperty("project.upload");
+    }
+
+    /**
+     * 上传文件
+     *
+     * @param file
+     */
+    public String uploadFile(MultipartFile file) {
+        if (file.isEmpty()) {
+            throw new ApiRuntimeException("文件流错误!");
+        }
+        String filePath = getPath();
+        if (!filePath.endsWith("/")) {
+            filePath = filePath.concat("/");
+        }
+        String path = filePath.concat("file/").concat(new SimpleDateFormat("yyMM/").format(new Date()));
+        if (!new File(path).exists()) {
+            new File(path).mkdirs();
+        }
+        try {
+            String fileName = UUID.randomUUID().toString().replace("-", "");
+            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
+            file.transferTo(new File(path.concat(fileName).concat(ext)));
+            return "/".concat(path).concat(fileName).concat(ext).replace(filePath, "");
+        } catch (IOException e) {
+            throw new ApiRuntimeException(500, "文件上传失败", e);
+        }
+    }
+}

+ 56 - 0
src/main/java/cn/fastfun/service/entity/AlarmCode.java

@@ -0,0 +1,56 @@
+package cn.fastfun.service.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.bridge.entity.IdEntity;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.*;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * @author bridge
+ */
+@Entity
+@Table(name = "t_alarm_code")
+@Setter
+@Getter
+@NoArgsConstructor
+public class AlarmCode extends IdEntity {
+
+    @ApiModelProperty(value = "协议", name = "protocolCode", required = true)
+    @Column(name = "protocol_code")
+    private String protocolCode;
+
+    @ApiModelProperty(value = "故障编码", name = "alarmCode", required = true)
+    @Column(name = "alarm_code")
+    private String alarmCode;
+
+    @ApiModelProperty(value = "故障级别", name = "alarmLevel", required = true)
+    @Column(name = "alarm_level")
+    private String alarmLevel;
+
+    @ApiModelProperty(value = "故障名称", name = "alarmTitle", required = true)
+    @Column(name = "alarm_title")
+    private String alarmTitle;
+
+    @ApiModelProperty(value = "文件地址", name = "fileUrl", required = true)
+    @Column(name = "file_url")
+    private String fileUrl;
+
+
+    public AlarmCode(Map<Integer, String> excelMap) {
+        setAlarmTitle(excelMap.get(0));
+        setAlarmCode(excelMap.get(1));
+        setAlarmLevel(excelMap.get(2));
+    }
+}

+ 15 - 0
src/main/java/cn/fastfun/service/impl/AlarmCodeServiceImp.java

@@ -0,0 +1,15 @@
+package cn.fastfun.service.impl;
+
+import cn.fastfun.service.entity.AlarmCode;
+import com.bridge.service.JpaService;
+import com.bridge.service.impl.JpaServiceImp;
+import org.springframework.stereotype.Service;
+
+/**
+ * 服务实现类
+ * Created by Bridge.
+ */
+@Service("alarmCodeService")
+public class AlarmCodeServiceImp extends JpaServiceImp<AlarmCode, String> implements JpaService<AlarmCode, String> {
+
+}

+ 12 - 0
src/main/java/cn/fastfun/service/repository/AlarmCodeRepository.java

@@ -0,0 +1,12 @@
+package cn.fastfun.service.repository;
+
+import cn.fastfun.service.entity.AlarmCode;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+
+/**
+* Created by Eye
+* @Author Bridge
+*/
+public interface AlarmCodeRepository extends JpaRepository<AlarmCode, String>, JpaSpecificationExecutor<AlarmCode> {
+}

+ 92 - 0
src/main/java/cn/fastfun/util/FileUtils.java

@@ -0,0 +1,92 @@
+package cn.fastfun.util;
+
+import org.springframework.util.ResourceUtils;
+
+import javax.imageio.ImageIO;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+/**
+ * @author bridge
+ * @date 2023/5/22  11:27
+ */
+public class FileUtils {
+
+    public static void outFile(HttpServletResponse response, String fileName, File file) {
+        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
+        //4.获取下载文件的输入流
+        try {
+            FileInputStream in = new FileInputStream(file);
+            //5.创建缓冲区
+            int len = 0;
+            byte[] buffer = new byte[2048];
+            //6.将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端。
+            ServletOutputStream out = response.getOutputStream();
+            while ((len = in.read(buffer)) > 0) {
+                out.write(buffer, 0, len);
+            }
+            //7.关闭流
+            in.close();
+            out.close();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void mergeImage(String filePath, String qr, String productTitle, String productCode, String num) {
+        try {
+            File template = new File("/home/label.png");
+            if (!template.exists()) {
+                template = ResourceUtils.getFile("classpath:label.png");
+            }
+            /* 1 读取第一张图片*/
+            BufferedImage imageFirst = ImageIO.read(template);
+            /* 2读取第二张图片 */
+            File fileTwo = new File(filePath + qr);
+            BufferedImage imageSecond = ImageIO.read(fileTwo);
+            //创建一个最底层画布 高和宽为第一章图片的高和宽
+            BufferedImage image = new BufferedImage(imageFirst.getWidth(), imageFirst.getHeight(), BufferedImage.TYPE_INT_ARGB);
+            //通过底图创建画笔
+            Graphics graphics = image.getGraphics();
+            //在底图上画第一张图
+            graphics.drawImage(imageFirst, 0, 0, null);
+            //在底图上画第二张图
+            graphics.drawImage(imageSecond, 300, 5, null);
+            //在图片上写文字
+            graphics.setFont(new Font("simsun", Font.PLAIN, 22));
+            graphics.setColor(Color.BLACK);
+            MyDrawString(productTitle, 100, 36, 1, graphics);
+//            graphics.drawString(productTitle, 100, 36);
+            MyDrawString(productCode, 100, 90, 0.88, graphics);
+            MyDrawString(num, 100, 146, 0.88, graphics);
+            //输出图片
+            fileTwo.delete();
+            File outFile = new File(filePath, qr);
+            ImageIO.write(image, "png", outFile);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void MyDrawString(String str, int x, int y, double rate, Graphics g) {
+        String tempStr = new String();
+        int orgStringWight = g.getFontMetrics().stringWidth(str);
+        int orgStringLength = str.length();
+        int tempx = x;
+        int tempy = y;
+        while (str.length() > 0) {
+            tempStr = str.substring(0, 1);
+            str = str.substring(1, str.length());
+            g.drawString(tempStr, tempx, tempy);
+            tempx = (int) (tempx + (double) orgStringWight / (double) orgStringLength * rate);
+        }
+    }
+}

+ 6 - 3
src/main/resources/application-dev.yml

@@ -3,17 +3,19 @@ server:
 spring:
   datasource:
     oss:
-      url: jdbc:mysql://192.168.0.40:3306/pdms_oss?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&tinyInt1isBit=false
+      driverClassName: com.mysql.cj.jdbc.Driver
+      url: jdbc:mysql://192.168.0.40:3306/pdms_oss?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&tinyInt1isBit=false&useSSL=false
       username: root
       password: Qx123456
     runtime:
-      url: jdbc:mysql://192.168.0.40:3306/fastfun?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
+      url: jdbc:mysql://192.168.0.40:3306/fastfun?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&useSSL=false
       username: root
       password: Qx123456
       driverClassName: com.mysql.cj.jdbc.Driver
   redis:
-    host: 192.168.0.41
+    host: 192.168.0.40
     port: 6379
+    password: jaikuai
   jpa:
     database: mysql
     hibernate:
@@ -33,6 +35,7 @@ logging:
 project:
   token-time: 360000
   secret-key: pdms-oss-api
+  upload: /Users/bridge/Downloads
 
 ok:
   http:

+ 10 - 10
src/test/java/com/bridge/AppTest.java

@@ -6,13 +6,13 @@ import org.junit.runner.RunWith;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.junit4.SpringRunner;
 
-@Slf4j
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-public class AppTest {
-    @Test
-    public void test() {
-
-    }
-
-}
+//@Slf4j
+//@RunWith(SpringRunner.class)
+//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+//public class AppTest {
+//    @Test
+//    public void test() {
+//
+//    }
+//
+//}