ImportNumberController.java 5.4 KB
package com.uccc.number.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.uccc.number.domain.NumberImportTask;
import com.uccc.number.domain.NumberQuery;
import com.uccc.number.service.ImportService;
import com.uccc.number.service.NumberService;
import com.uccc.number.service.RabbitMqService;
import com.uccc.pretty.common.Result;
import com.uccc.pretty.common.SystemLog;
import com.uccc.pretty.constants.ErrorCode;
import com.uccc.number.exception.ApiException;
import com.uccc.pretty.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;

import static com.uccc.pretty.constants.ActionEnum.EXPORT_NUM_FILE;
import static com.uccc.pretty.constants.ResultEnum.RESULT_ERR;
import static com.uccc.pretty.constants.ResultEnum.RESULT_OK;

/**
 * Created by bert on 2021-09-15 15:34
 */

@RestController
@RequestMapping("/import_number/")
public class ImportNumberController {
    private Logger logger = LoggerFactory.getLogger(ImportNumberController.class);

    @Autowired
    private RabbitMqService rabbitMqService;
    @Autowired
    private ImportService importService;
    @Autowired
    private NumberService numberService;

    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public Result upload(@RequestParam("file") MultipartFile file,
                         @RequestParam String status, @RequestParam String ip, HttpServletRequest request) {
        Result result = new Result();
        if (file.isEmpty()) throw new ApiException(ErrorCode.FILE_IS_EMPTY);
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        logger.info("file:{}", fileType);
        if (!fileType.equals(".xlsx")) throw new ApiException(ErrorCode.FILE_PREFIX_WRONG);
        //当前时间的 时分秒
        String fileName= DateUtils.getDate() + "_" + DateUtils.getTimeWithoutSecond().replaceAll(":", "_")+fileType;
//        String path = "/Users/bert/Desktop/";
        String path = "/opt/pretty-server/import_files/";
        File checkFile = new File( path + fileName);
        if (checkFile.exists()) throw new ApiException(ErrorCode.FILE_EXIST);

        InputStream is;
        try {
            is = file.getInputStream();
            FileOutputStream fos = new FileOutputStream(path + fileName);
            byte[] b = new byte[1024];
            while ((is.read(b)) != -1) {
                fos.write(b);// 写入数据
            }
            is.close();
            fos.close();// 保存数据
            File saveFile = new File( path + fileName);
            if (saveFile.exists()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", fileName);
                jsonObject.put("cts", System.currentTimeMillis());
                jsonObject.put("type", fileType);
                jsonObject.put("path", path);
                jsonObject.put("oldName",file.getOriginalFilename());
                jsonObject.put("status", status);
                rabbitMqService.sendMsg(jsonObject.toJSONString());
                //
                result.setCode(RESULT_OK.getCode());
                result.setMessage(RESULT_OK.getMessage());
            }else {
                result.setCode(RESULT_ERR.getCode());
                result.setMessage(RESULT_ERR.getMessage());
            }
            String token = request.getHeader("token");
            String userId = JWT.decode(token).getAudience().get(0);
            SystemLog systemLog = new SystemLog(Long.parseLong(userId),EXPORT_NUM_FILE.getMessage(),EXPORT_NUM_FILE.getMessage(),new Date(),result.getMessage(),ip);
            importService.sendSystemLogToRabbitMq(JSONObject.toJSONString(systemLog));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }



        return result;
    }


    @RequestMapping(value = "tasks",method = RequestMethod.GET)
    public Result numberImportList (@RequestParam(name = "limit") Integer limit,
                             @RequestParam(name = "page") Integer page,
                             @RequestParam(name = "status", required = false) Integer status) throws NullPointerException{

        Result result = new Result();
        List<NumberImportTask> numberImportTaskList = importService.getNumberImportTask(limit, page, status);
        if (numberImportTaskList.size() > 0) {
            int count = importService.getNumberImportTaskCount(status);
            result.setCode(RESULT_OK.getCode());
            result.setMessage(RESULT_OK.getMessage());
            JSONObject json = new JSONObject();
            json.put("count", count);
            json.put("rows", numberImportTaskList);
            result.setData(json);
        }else {
            throw new ApiException(ErrorCode.Export_TASK_NULL);
        }
        return result;
    }

    /**
     *
     * @param query
     * @return
     */
    @RequestMapping(value = "get",method = RequestMethod.POST)
    public Result getNumbers(@RequestBody NumberQuery query) throws IOException {
        return new Result(RESULT_OK.getCode(), RESULT_OK.getMessage(), numberService.getESNumbers(query));
    }
}