@ApiOperation(value="下载原始观测数据",notes = "")
@RequestMapping(value = "/data/export",method = RequestMethod.GET)
public ResponseEntity<Object> exportLocalFile(HttpServletRequest request,HttpServletResponse response,@NotNull @RequestParam("id") Long id){
byte[] resp = null;
try{
resp = storeFileService.exportLocalFile(request,response,id);
}catch (Exception e){
log.error(e.getMessage());
ResponseDto responseDto = new ResponseDto();
responseDto.setCode("400");
responseDto.setMessage(e.getMessage());
responseDto.setSuccess(false);
return new ResponseEntity<>(responseDto, HttpStatus.OK);
}
return new ResponseEntity<>(resp, HttpStatus.OK);
}
service层
@Override
public byte[] exportLocalFile(HttpServletRequest request, HttpServletResponse response, Long id) throws Exception{
//根据path判断文件是否存在
StoreFile storeFile = null;
try{
storeFile = this.queryStoreFileById(id);
}catch (Exception e){
log.error("查询数据存储文件失败,id:{},message:{}",id,e.getLocalizedMessage());
throw new BusinessException(ErrorCode.BUSINESS_ERROR,"查询存储文件失败,请查看日志");
}
if(ObjectUtils.isEmpty(storeFile)){
throw new BusinessException(ErrorCode.BUSINESS_ERROR,"查询的存储文件不存在");
}
if(StringUtils.isEmpty(storeFile.getPath())){
throw new BusinessException(ErrorCode.BUSINESS_ERROR,"查询的存储文件路径不存在");
}
//存储文件路径+文件名
String fullPath = storeFile.getPath().replace("%20"," ");
//获取文件名
int fileNameBeginIndex = storeFile.getPath().lastIndexOf('/');
String fileName = storeFile.getPath().substring(fileNameBeginIndex+1);
File file = new File(fullPath);
//判断文件是否存在
if(file.exists()){
//判断文件大小,单位MB
long fileSize = FileUtils.sizeOf(file)/1024/1024;
if(fileSize > 500){
throw new BusinessException(ErrorCode.BUSINESS_ERROR,"查询的存储文件大小超出限制");
}
// 配置文件下载
// response.setHeader("content-type", "application/octet-stream");
// response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
log.info("Download the GNS file successfully!");
} catch (Exception e) {
log.error("Download the GNS file failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} else {//对应文件不存在
throw new BusinessException(ErrorCode.BUSINESS_ERROR,"下载的文件不存在");
}
}
异常封装类
@Data
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = -4128652785823304495L;
private ErrorCode errorCode;
private String message;
private Integer code;
public BusinessException(ErrorCode errorCode) {
super();
this.errorCode = errorCode;
}
public BusinessException(ErrorCode errorCode, String message) {
super();
this.errorCode = errorCode;
this.message = message;
}
}
public enum ErrorCode {
/**
* 错误码不需要定义错误描述,直接抛出异常
*/
METHOD_NOT_FOUND_ERROR(404),
UNKNOWN_ERROR(500),
METHOD_NOT_SUPPORT(403),
PARAMS_INVALID(405),
DATA_NOT_EXIST(406),
DATA_DUPLICATION(407),
BUSINESS_ERROR(408),
MISSING_PARAMS(409),
PARAMS_TYPE_INVALID(402),
METHOD_ARGUMENT_NOT_VALID(400),
RECEIVER_ERROR(501),
UNAUTHORIZED(401),
/**
* feign调用错误
*/
FEIGN_CALL_ERROR(100000),
LOGIN_USER_OR_PWD_ERROR(100001),
/**
* 角色信息删除失败
*/
ROLE_DELETE_FAILED(400002),
/**
* 下载的文件不存在
*/
FILE_NOT_FOUND(400003),
/**
* 下载文件失败
*/
FILE_DOWNLOAD_FAIL(400004),
;
private final Integer code;
ErrorCode(Integer code) {
this.code = code;
}
public Integer getKey() {
return code;
}
}
全局异常处理类
package com.zhdgps.znetlbs.exception;
import com.zhdgps.cloud.common.constant.Constants;
import com.zhdgps.cloud.common.exception.BusinessException;
import com.zhdgps.cloud.common.exception.EncryptException;
import com.zhdgps.cloud.common.exception.ErrorCode;
import com.zhdgps.cloud.common.http.response.ResponseHelper;
import com.zhdgps.znetlbs.dto.es.ResponseDto;
import com.zhdgps.znetlbs.remote.http.HttpGNSSResponse;
import com.zhdgps.znetlbs.remote.http.service.EncryptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Optional;
@RestControllerAdvice
@Slf4j
public class GlobalException {
@Autowired
EncryptService encryptService;
/**
* 统一异常处理
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> exceptionHandler(Exception e) {
log.error(Constants.HTTP_RES_CODE_500_VALUE, e);
return ResponseHelper.failed(Constants.HTTP_RES_CODE_500_VALUE);
}
/**
* 业务异常类统一处理
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Object> businessExceptionHandler(BusinessException e) {
return ResponseHelper.failed(e.getErrorCode().getKey(), e.getMessage());
}
/**
* 参数绑定异常
* @param e
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class, MissingServletRequestParameterException.class})
public ResponseEntity<Object> businessExceptionHandler(Exception e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
String message = Optional.ofNullable(exception.getBindingResult().getFieldError())
.flatMap(fieldError -> Optional.ofNullable(fieldError.getDefaultMessage())).orElse("");
return ResponseHelper.failed(ErrorCode.MISSING_PARAMS.getKey(), StringUtils.isEmpty(message) ? "缺少必填参数" : message);
}
return ResponseHelper.failed(ErrorCode.MISSING_PARAMS.getKey(), "缺少必填参数");
}
/**
* 基准站权限异常
* @param e
* @return
*/
@ExceptionHandler(EncryptException.class)
public ResponseEntity<Object> authExceptionHandler(EncryptException e) {
HttpGNSSResponse response = new HttpGNSSResponse(e.getCode() + "", e.getMessage());
return new ResponseEntity<>(encryptService.encryptData(response), HttpStatus.OK);
}
@ExceptionHandler(HardwareException.class)
public ResponseEntity<Object> hardwareExceptionHandler(HardwareException e) {
ResponseDto responseDto = new ResponseDto();
responseDto.setErrorCode(e.getErrorCode());
responseDto.setErrorMessage(e.getErrorMessage());
return new ResponseEntity<>(encryptService.encryptData(responseDto), HttpStatus.OK);
}
}