Commit d4868ca0 authored by huangcb's avatar huangcb

新增OCR身份证正面识别功能接口

parent 5bca1ceb
......@@ -106,6 +106,11 @@
<artifactId>druid-spring-boot-starter</artifactId>
<version>${alibaba-druid.version}</version>
</dependency>
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.12.0</version>
</dependency>
</dependencies>
<dependencyManagement>
......
package com.esv.freight.file.common.component;
import com.baidu.aip.ocr.AipOcr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
/**
* @description: 百度智能云AipOcr组件
* @project: freight-file-service
* @name: com.esv.freight.file.common.component.AipOcrComponent
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 9:35
* @version:1.0
*/
@Component
@RefreshScope
public class AipOcrComponent {
@Value("${baidu.ocr.app_id}")
private String APP_ID;
@Value("${baidu.ocr.api_key}")
private String API_KEY;
@Value("${baidu.ocr.secret_key}")
private String SECRET_KEY;
private static AipOcr client;
public AipOcr getClient() {
if (null == client) {
System.out.println("APP_ID="+APP_ID);
System.out.println("API_KEY="+API_KEY);
System.out.println("SECRET_KEY="+SECRET_KEY);
client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
}
return client;
}
}
......@@ -18,6 +18,7 @@ public class ECode {
public static final ECode PARAM_ERROR = new ECode(600, "参数不合法");
public static final ECode TOKEN_INVALID = new ECode(601, "无效的Token");
public static final ECode TOKEN_EXPIRED = new ECode(602, "Token已过期");
public static final ECode THIRD_PARTY_ERROR = new ECode(605, "请求第三方服务失败");
public ECode(int code, String message) {
this.code = code;
......
package com.esv.freight.file.module.file.constants;
import org.apache.commons.lang3.StringUtils;
/**
* @description: 文件类型枚举
* @project: freight-file-service
* @name: com.esv.freight.file.module.file.constants.FileTypeEnum
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 11:20
* @version:1.0
*/
public enum FileTypeEnum {
UNDEFINED("undefined", "text/plain"),
IMAGE("image", "application/x-jpg"),
PDF("pdf", "application/pdf"),
EXCEL("excel", "application/vnd.ms-excel"),
APK("apk", "application/vnd.android.package-archive");
private String fileType;
private String contentType;
FileTypeEnum(String fileType, String contentType) {
this.fileType = fileType;
this.contentType = contentType;
}
public static FileTypeEnum getEnumByType(String fileType) {
if (StringUtils.isBlank(fileType)){
return FileTypeEnum.UNDEFINED;
}
for (FileTypeEnum typeEnum : FileTypeEnum.values()) {
if (typeEnum.getFileType().equals(fileType)) {
return typeEnum;
}
}
return FileTypeEnum.UNDEFINED;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
package com.esv.freight.file.module.delete.controller;
package com.esv.freight.file.module.file.controller;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.response.EResponse;
import com.esv.freight.file.common.validator.groups.ValidatorDelete;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.service.FileMetaService;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileMetaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
......@@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* @description: 文件删除Controller
* @project: freight-file-service
* @name: com.esv.freight.file.module.delete.controller.DeleteController
* @name: DeleteController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/14 19:37
......
package com.esv.freight.file.module.download.controller;
package com.esv.freight.file.module.file.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.response.EResponse;
import com.esv.freight.file.common.validator.groups.ValidatorDetail;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.service.FileMetaService;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileMetaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
......@@ -15,7 +15,7 @@ import javax.servlet.http.HttpServletResponse;
/**
* @description: 文件下载Controller
* @project: freight-file-service
* @name: com.esv.freight.file.module.download.controller.DownloadController
* @name: DownloadController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/14 17:06
......
package com.esv.freight.file.module.upload.controller;
package com.esv.freight.file.module.file.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.response.EResponse;
import com.esv.freight.file.common.validator.groups.ValidatorInsert;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.service.FileMetaService;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileMetaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
......
package com.esv.freight.file.module.upload.dao;
package com.esv.freight.file.module.file.dao;
import com.esv.freight.file.module.upload.entity.FileMetaEntity;
import com.esv.freight.file.module.file.entity.FileMetaEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
......
package com.esv.freight.file.module.upload.entity;
package com.esv.freight.file.module.file.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
......
package com.esv.freight.file.module.upload.form;
package com.esv.freight.file.module.file.form;
import com.esv.freight.file.common.validator.groups.ValidatorDelete;
import com.esv.freight.file.common.validator.groups.ValidatorDetail;
......
package com.esv.freight.file.module.upload.service;
package com.esv.freight.file.module.file.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.module.upload.entity.FileMetaEntity;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.vo.FileVO;
import com.esv.freight.file.module.file.entity.FileMetaEntity;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.vo.FileVO;
import javax.servlet.http.HttpServletResponse;
......
package com.esv.freight.file.module.upload.service.impl;
package com.esv.freight.file.module.file.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.freight.file.common.constants.DbDeletedEnum;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.util.AESSecretUtils;
import com.esv.freight.file.module.upload.dao.FileMetaDao;
import com.esv.freight.file.module.upload.entity.FileMetaEntity;
import com.esv.freight.file.module.upload.form.FileForm;
import com.esv.freight.file.module.upload.service.FileMetaService;
import com.esv.freight.file.module.upload.vo.FileVO;
import com.esv.freight.file.module.file.constants.FileTypeEnum;
import com.esv.freight.file.module.file.dao.FileMetaDao;
import com.esv.freight.file.module.file.entity.FileMetaEntity;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileMetaService;
import com.esv.freight.file.module.file.vo.FileVO;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
......@@ -73,7 +74,7 @@ public class FileMetaServiceImpl extends ServiceImpl<FileMetaDao, FileMetaEntity
ObjectId objectId;
String fileId;
try {
objectId = gridFsTemplate.store(inputStream, fileName, getFileContentType(fileType));
objectId = gridFsTemplate.store(inputStream, fileName, FileTypeEnum.getEnumByType(fileType).getContentType());
fileId = objectId.toString();
} catch (Exception e) {
log.error("存储文件数据时发生错误");
......@@ -165,7 +166,8 @@ public class FileMetaServiceImpl extends ServiceImpl<FileMetaDao, FileMetaEntity
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
response.setCharacterEncoding("UTF-8");
response.setContentLength((int) gridFSFile.getLength());
response.setContentType(this.getFileContentType(fileMetaEntity.getFileType()));
FileTypeEnum fileTypeEnum = FileTypeEnum.getEnumByType(fileMetaEntity.getFileType());
response.setContentType(fileTypeEnum.getContentType());
GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());
......@@ -271,35 +273,6 @@ public class FileMetaServiceImpl extends ServiceImpl<FileMetaDao, FileMetaEntity
}
}
/**
* description 获取文件的ContentType
* param [fileType]
* return java.lang.String
* author Administrator
* createTime 2020/04/14 14:47
**/
private String getFileContentType(String fileType) {
String contentType;
switch (fileType) {
case "image":
contentType = "application/x-jpg";
break;
case "pdf":
contentType = "application/pdf";
break;
case "excel":
contentType = "application/vnd.ms-excel";
break;
case "apk":
contentType = "application/vnd.android.package-archive";
break;
default:
contentType = "undefined";
break;
}
return contentType;
}
/**
* 文件下载错误返回
* @param errorMsg
......
package com.esv.freight.file.module.upload.vo;
package com.esv.freight.file.module.file.vo;
import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
......
package com.esv.freight.file.module.ocr.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.response.ECode;
import com.esv.freight.file.common.response.EResponse;
import com.esv.freight.file.module.ocr.form.IdCardForm;
import com.esv.freight.file.module.ocr.service.OcrHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description: Ocr Controller
* @project: freight-file-service
* @name: com.esv.freight.file.module.ocr.controller.OcrController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 10:24
* @version:1.0
*/
@Slf4j
@RestController
@RequestMapping("/ocr")
@RefreshScope
public class OcrController {
private OcrHistoryService ocrHistoryService;
@Autowired
public OcrController(OcrHistoryService ocrHistoryService) {
this.ocrHistoryService = ocrHistoryService;
}
/**
* description 身份证正面识别
* param []
* return com.esv.freight.file.common.response.EResponse
* author Administrator
* createTime 2020/04/15 10:31
**/
@PostMapping("/idcard/front")
public EResponse OcrIdCardFront(@RequestBody @Validated IdCardForm idCardForm) throws EException {
// 参数校验
if (idCardForm.isNeedFileInfo()) {
if (null == idCardForm.getFileName()) {
return EResponse.error(ECode.PARAM_ERROR.code(), "参数fileName不能为空");
}
}
JSONObject data = ocrHistoryService.OcrIdCard(idCardForm);
return EResponse.ok(data);
}
}
package com.esv.freight.file.module.ocr.dao;
import com.esv.freight.file.module.ocr.entity.OcrHistoryEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 图片OCR识别记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-15 10:52:08
*/
@Mapper
public interface OcrHistoryDao extends BaseMapper<OcrHistoryEntity> {
}
package com.esv.freight.file.module.ocr.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 图片OCR识别记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-15 10:52:08
*/
@Data
@TableName("base_ocr_history")
public class OcrHistoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 文件MD5值
*/
private String fileMd5;
/**
* OCR识别结果
*/
private String ocrResult;
/**
* 创建者
*/
private String createUser;
/**
* 修改者
*/
private String updateUser;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
}
package com.esv.freight.file.module.ocr.form;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
/**
* @description:
* @project: freight-file-service
* @name: com.esv.freight.file.module.ocr.form.IdCardForm
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 10:08
* @version:1.0
*/
@Data
public class IdCardForm {
@NotBlank(message = "参数image不能为空")
private String image;
@Length(max = 50, message = "参数fileName长度不合法")
private String fileName;
private boolean needFileInfo;
}
package com.esv.freight.file.module.ocr.service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.module.ocr.entity.OcrHistoryEntity;
import com.esv.freight.file.module.ocr.form.IdCardForm;
/**
* 图片OCR识别记录表
*
* @author 黄朝斌
* @email huangchaobin@esvtek.com
* @date 2020-04-15 10:52:08
*/
public interface OcrHistoryService extends IService<OcrHistoryEntity> {
/**
* description 身份证正面识别
* param [idCardForm]
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/04/15 10:10
**/
JSONObject OcrIdCard(IdCardForm idCardForm) throws EException;
}
\ No newline at end of file
package com.esv.freight.file.module.ocr.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esv.freight.file.common.component.AipOcrComponent;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.response.ECode;
import com.esv.freight.file.module.file.constants.FileTypeEnum;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileMetaService;
import com.esv.freight.file.module.file.vo.FileVO;
import com.esv.freight.file.module.ocr.dao.OcrHistoryDao;
import com.esv.freight.file.module.ocr.entity.OcrHistoryEntity;
import com.esv.freight.file.module.ocr.form.IdCardForm;
import com.esv.freight.file.module.ocr.service.OcrHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import java.util.Base64;
import java.util.HashMap;
@Service("ocrHistoryService")
@Slf4j
public class OcrHistoryServiceImpl extends ServiceImpl<OcrHistoryDao, OcrHistoryEntity> implements OcrHistoryService {
private AipOcrComponent aipOcrComponent;
private FileMetaService fileMetaService;
public OcrHistoryServiceImpl(AipOcrComponent aipOcrComponent, FileMetaService fileMetaService) {
this.aipOcrComponent = aipOcrComponent;
this.fileMetaService = fileMetaService;
}
@Override
public JSONObject OcrIdCard(IdCardForm idCardForm) throws EException {
JSONObject resultJson = new JSONObject();
byte[] data = Base64.getDecoder().decode(idCardForm.getImage());
// 通过文件的MD5值判断是否有历史OCR结果
String fileMD5 = DigestUtils.md5Hex(data);
OcrHistoryEntity queryEntity = new OcrHistoryEntity();
queryEntity.setFileMd5(fileMD5);
QueryWrapper<OcrHistoryEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.setEntity(queryEntity);
OcrHistoryEntity ocrHistoryEntityDB = this.getOne(queryWrapper);
String ocrInfo;
if (null == ocrHistoryEntityDB) {
/*************************************** 调用第三方OCR服务 *************************************/
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<>(2);
// 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:true:检测朝向;false:不检测朝向。
options.put("detect_direction", "true");
// 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启
options.put("detect_risk", "false");
// front:身份证含照片的一面;back:身份证带国徽的一面
String idCardSide = "front";
AipOcr client = aipOcrComponent.getClient();
org.json.JSONObject ocrRes;
try {
ocrRes = client.idcard(data, idCardSide, options);
log.info(ocrRes.toString());
} catch (Exception e) {
log.error("请求OCR服务时发生错误");
log.error(e.getMessage(), e);
throw new EException(ECode.THIRD_PARTY_ERROR.code(), "请求OCR服务时发生错误");
}
ocrInfo = ocrRes.toString();
/*************************************** 调用第三方OCR服务 *************************************/
// 保存OCR结果
OcrHistoryEntity ocrHistoryEntity = new OcrHistoryEntity();
ocrHistoryEntity.setFileMd5(fileMD5);
ocrHistoryEntity.setOcrResult(ocrInfo);
this.baseMapper.insert(ocrHistoryEntity);
} else {
ocrInfo = ocrHistoryEntityDB.getOcrResult();
}
JSONObject ocrInfoJson = getIdCardOcrInfo(ocrInfo);
resultJson.put("ocrInfo", ocrInfoJson);
// 判断是否需要存储文件
if (idCardForm.isNeedFileInfo()) {
FileForm fileForm = new FileForm();
fileForm.setFileData(idCardForm.getImage());
fileForm.setFileName(idCardForm.getFileName());
fileForm.setFileType(FileTypeEnum.IMAGE.getFileType());
FileVO fileVO = fileMetaService.uploadFile(fileForm);
resultJson.put("fileInfo", fileVO);
}
return resultJson;
}
/**
* description 获取OCR信息
* param [ocrInfo]
* return com.alibaba.fastjson.JSONObject
* author Administrator
* createTime 2020/04/15 11:04
**/
private JSONObject getIdCardOcrInfo(String ocrInfo) throws EException {
JSONObject ocrInfoJson = new JSONObject();
JSONObject jsonObject = JSONObject.parseObject(ocrInfo);
if (!"normal".equals(jsonObject.getString("image_status"))) {
throw new EException(1001, "OCR识别失败");
}
JSONObject wordsResult = jsonObject.getJSONObject("words_result");
ocrInfoJson.put("name", wordsResult.getJSONObject("姓名").getString("words"));
ocrInfoJson.put("id", wordsResult.getJSONObject("公民身份号码").getString("words"));
ocrInfoJson.put("sex", wordsResult.getJSONObject("性别").getString("words"));
ocrInfoJson.put("nation", wordsResult.getJSONObject("民族").getString("words"));
ocrInfoJson.put("birthdate", wordsResult.getJSONObject("出生").getString("words"));
return ocrInfoJson;
}
}
\ No newline at end of file
......@@ -55,3 +55,8 @@ file:
register: image=2,pdf=10,excel=5,apk=100
download:
base-url: http://127.0.0.1:8002/file/download/direct/
baidu:
ocr:
app_id: 19433262
api_key: iXr2xpoGp3GPshCWkiW92W2G
secret_key: 6xzVIG8C3tQslR9zsM7q6gRYLNLc8ISB
\ No newline at end of file
......@@ -49,3 +49,8 @@ aes:
file:
download:
base-url: http://192.168.31.248:8082/file/download/direct/
baidu:
ocr:
app_id: 19433262
api_key: iXr2xpoGp3GPshCWkiW92W2G
secret_key: 6xzVIG8C3tQslR9zsM7q6gRYLNLc8ISB
\ No newline at end of file
<?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.esv.freight.file.module.ocr.dao.OcrHistoryDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="com.esv.freight.file.module.ocr.entity.OcrHistoryEntity" id="ocrHistoryMap">
<result property="id" column="id"/>
<result property="fileMd5" column="file_md5"/>
<result property="ocrResult" column="ocr_result"/>
<result property="createUser" column="create_user"/>
<result property="updateUser" column="update_user"/>
<result property="createTime" column="create_time"/>
<result property="updateTime" column="update_time"/>
</resultMap>
</mapper>
\ No newline at end of file
<?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.esv.freight.file.module.upload.dao.FileMetaDao">
<mapper namespace="com.esv.freight.file.module.file.dao.FileMetaDao">
<!-- 可根据自己的需求,是否要使用 -->
<resultMap type="com.esv.freight.file.module.upload.entity.FileMetaEntity" id="fileMetaMap">
<resultMap type="com.esv.freight.file.module.file.entity.FileMetaEntity" id="fileMetaMap">
<result property="id" column="id"/>
<result property="callSystem" column="call_system"/>
<result property="fileId" column="file_id"/>
......@@ -17,7 +17,7 @@
<result property="deleteTime" column="delete_time"/>
</resultMap>
<update id="logicDelete" parameterType="com.esv.freight.file.module.upload.entity.FileMetaEntity">
<update id="logicDelete" parameterType="com.esv.freight.file.module.file.entity.FileMetaEntity">
update base_file_meta
set deleted = #{deleted},
delete_time = #{deleteTime}
......
package com.esv.freight.file;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @description:
* @project: freight-file-service
* @name: com.esv.freight.file.BaseController
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 14:09
* @version:1.0
*/
@Slf4j
@Data
public class BaseTestController {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void after() {
log.info("=================================== Test End ===================================");
}
}
package com.esv.freight.file.module.upload.controller;
package com.esv.freight.file.module.file.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.BaseTestController;
import com.esv.freight.file.common.response.ECode;
import lombok.extern.slf4j.Slf4j;
import org.junit.*;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
......@@ -37,28 +36,12 @@ import java.util.Base64;
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UploadControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
public class UploadControllerTest extends BaseTestController {
private static String fileId;
private static String fileUrl;
@Before
public void before() {
log.info("=================================== Test Start ===================================");
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void after() {
log.info("=================================== Test End ===================================");
}
@Test
public void a1_uploadSingleFile_success_test() throws Exception {
String url = "/upload/single";
......@@ -68,18 +51,11 @@ public class UploadControllerTest {
String filepath = "D:\\test\\1366x768_107480_8.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes = output.toByteArray();
reqJson.put("fileType", "image");
reqJson.put("fileData", Base64.getEncoder().encodeToString(bytes));
reqJson.put("fileData", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("fileName", "1366x768_107480_8.jpg");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
......@@ -104,18 +80,11 @@ public class UploadControllerTest {
String filepath = "D:\\test\\1366x768_107480_8.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes = output.toByteArray();
reqJson.put("fileType", "test");
reqJson.put("fileData", Base64.getEncoder().encodeToString(bytes));
reqJson.put("fileData", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("fileName", "1366x768_107480_8.jpg");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
......@@ -136,20 +105,12 @@ public class UploadControllerTest {
// 构造数据
String filepath = "D:\\test\\方正粗黑宋简体.ttf";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes = output.toByteArray();
byte[] bytes = IOUtils.toByteArray(new FileInputStream(new File(filepath)));
reqJson.put("fileType", "image");
reqJson.put("fileData", Base64.getEncoder().encodeToString(bytes));
reqJson.put("fileName", "方正粗黑宋简体.ttf");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
......@@ -170,7 +131,7 @@ public class UploadControllerTest {
String url = "/download/direct/"+dUrl;
mockMvc.perform(MockMvcRequestBuilders.get(url))
this.getMockMvc().perform(MockMvcRequestBuilders.get(url))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
......@@ -183,7 +144,7 @@ public class UploadControllerTest {
// 构造数据
reqJson.put("id", fileId);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
......@@ -205,7 +166,7 @@ public class UploadControllerTest {
// 构造数据
reqJson.put("id", fileId);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
......
package com.esv.freight.file.module.ocr.controller;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.BaseTestController;
import com.esv.freight.file.common.response.ECode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
/**
* @description:
* @project: freight-file-service
* @name: com.esv.freight.file.module.ocr.controller.OcrControllerTest
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/04/15 13:53
* @version:1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OcrControllerTest extends BaseTestController {
/**
* OCR识别成功
**/
@Test
public void a1_OcrIdCardFront_success_test() throws Exception {
String url = "/ocr/idcard/front";
JSONObject reqJson = new JSONObject();
// 构造数据
String filepath = "D:\\test\\idcard_front.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
reqJson.put("image", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("needFileInfo", false);
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.SUCCESS.code(), result.getIntValue("code"));
Assert.assertTrue(result.getJSONObject("data").containsKey("ocrInfo"));
}
/**
* 参数错误
**/
@Test
public void a2_OcrIdCardFront_params_error_test() throws Exception {
String url = "/ocr/idcard/front";
JSONObject reqJson = new JSONObject();
// 构造数据
String filepath = "D:\\test\\idcard_front.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
reqJson.put("image", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("needFileInfo", true);
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(ECode.PARAM_ERROR.code(), result.getIntValue("code"));
}
/**
* OCR识别失败
**/
@Test
public void a3_OcrIdCardFront_ocr_error_test() throws Exception {
String url = "/ocr/idcard/front";
JSONObject reqJson = new JSONObject();
// 构造数据
String filepath = "D:\\test\\test模板.png";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
reqJson.put("image", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("needFileInfo", false);
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(reqJson.toJSONString()))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
String responseStr = mvcResult.getResponse().getContentAsString();
log.info(responseStr);
JSONObject result = JSONObject.parseObject(responseStr);
Assert.assertEquals(1001, result.getIntValue("code"));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment