package com.vcredit.ddcash.server.web.controller.common;

import com.vcredit.ddcash.server.commons.model.FtpParam;
import com.vcredit.ddcash.server.commons.net.FTPClient;
import com.vcredit.ddcash.server.commons.net.FTPService;
import com.vcredit.ddcash.server.model.entity.loan.CustomerEntity;
import com.vcredit.ddcash.server.service.loan.CustomerService;
import com.vcredit.framework.exception.BusinessException;
import com.vcredit.framework.utils.CommonUtils;
import com.vcredit.framework.utils.HttpClientUtils;
import com.vcredit.functions.model.dto.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.net.SocketException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 文件下载
*/
@Path("/client/imageFiles")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class ClientImageViewController {
private static final Logger logger = LoggerFactory.getLogger(ClientImageViewController.class);
/**
* 身份证照片存放路径
*/
@Value("${identity.disk.save.path}")
private String diskSavePath;

@Value("${identity.disk.read.path}")
private String diskReadPath;

@Value("${identity.disk.customerfile.path}")
private String diskcustomerFilePath;

@Value("${headPicture.disk.save.path}")
private String headPictureSavePath;

@Value("${creditSignature.disk.save.path}")
private String creditSignature;

@Autowired
private CustomerService customerService;

@Autowired
private FTPService ftpService;

/**
* 微信展示
*
* @param paramMap 待下载文件名称 微信ID
*/
@POST
@Path("/showIdentity")
public Response viewIdentityImages(Map<String, Object> paramMap) {
OutputStream out = null;
FileInputStream in = null;
String img64 = null;
try {
byte[] content = null;
String type = CommonUtils.getValue(paramMap, "type");
String customerId = CommonUtils.getValue(paramMap, "customerId");
if (StringUtils.isBlank(type)) {
return Response.fail("type不能为空");
}
if (StringUtils.isBlank(customerId)) {
return Response.fail("customerId不能为空");
}
if ("headPicture".equals(type)) {
// 创建文件名
String fileName = headPictureSavePath + "/" + customerId + "/" + customerId + "_" + type + ".jpg";
File file = new File(fileName);
if (!file.exists()) {
//没有找到以customerId命名的文件,查询是否以openId命名
CustomerEntity customer = customerService.selectById(customerId);
String openId = customer==null?null:customer.getOpenId();
if (customer == null) {
return Response.fail("该customerId对应的用户不存在");
} else if (openId != null && !"null".equals(openId)) {
fileName = headPictureSavePath + "/" + openId + "/" + openId + "_" + type + ".jpg";
file = new File(fileName);
if (file.exists()) {
content = FileUtils.readFileToByteArray(file);
} else {
//没有找到以openID和customerId命名的文件,说明文件不存在
return Response.fail("file is not exist");
}
} else {
return Response.fail("file is not exist");
}
} else {
content = FileUtils.readFileToByteArray(file);
}
} else if ("dbc_signature".equals(type) || "wmc_signature".equals(type)) {
String fileName = creditSignature + "/" + customerId + "/" + customerId + "_" + type + ".jpg";
File file = new File(fileName);
if (!file.exists()) {
return Response.fail("file is not exist");
} else {
content = FileUtils.readFileToByteArray(file);
}

} else {
// 创建文件名
String fileName = customerId + "/" + customerId + "_" + type + ".jpg";
try {
logger.info("viewIdentityImages customerIdfile path:" + diskReadPath + fileName);
content = HttpClientUtils.getMethodGetContent(diskReadPath + fileName);
} catch (Exception e) {
logger.info("viewIdentityImages fail:" + e);
}
if (content == null) {
//没有找到以customerId命名的文件,查询是否以openId命名
CustomerEntity customer = customerService.selectById(customerId);
String openId = customer==null?null:customer.getOpenId();
logger.info(" showIdentity fileName is " + fileName);
if (customer == null) {
return Response.fail("该customerId对应的用户不存在");
} else if (null != openId && "null".equals(openId)) {
fileName = openId + "/" + openId + "_" + type + ".jpg";
try {
logger.info("viewIdentityImages openIdfile path:" + diskReadPath + fileName);
content = HttpClientUtils.getMethodGetContent(diskReadPath + fileName);
} catch (Exception e) {
logger.info("viewIdentityImages fail:" + e);
}
} else {
//没有找到以openID和customerId命名的文件,说明文件不存在
return Response.fail("file is not exist");
}

}
}
img64 = Base64.encodeBase64String(content);
} catch (Exception e) {
logger.error("get random image fail", e);
return Response.fail("errorInfo", "system error");
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
logger.error("close resource error", e);
}
}
return Response.success("接口调用成功", img64);
}

/**
* 上传身份证图片
*
* @param paramMap
* @throws Exception
* @throws BusinessException
*/
@POST
@Path("/uploadImage")
public Response uploadClientImage(Map<String, Object> paramMap) throws Exception {
OutputStream out = null;
String fileName = null;
String fileUploadPath = null;
String type = CommonUtils.getValue(paramMap, "type");
String customerId = CommonUtils.getValue(paramMap, "customerId");
String content = CommonUtils.getValue(paramMap, "content");
byte[] bytes = Base64Utils.decodeFromString(content);

if ("front".equals(type) || "back".equals(type) || "similarity_person".equals(type)
|| "re_front".equals(type) || "re_back".equals(type) || "re_similarity_person".equals(type)
|| "new_front".equals(type) || "new_back".equals(type) || "new_similarity_person".equals(type)
|| "facepair_0".equals(type) || "facepair_1".equals(type) || "facepair_2".equals(type)) {
fileName = customerId + "_" + type + ".jpg";
logger.info("uploadClientImage fileName:"+diskSavePath+fileName);
FtpParam param = new FtpParam(diskSavePath , customerId + "/", fileName);
FTPClient ftpClient=new FTPClient();
ftpService.connect(ftpClient);
try {
logger.info("uploadClientImage content.length:"+bytes.length);
if (ftpService.uploadImg(ftpClient,diskSavePath,param,new ByteArrayInputStream(bytes))) {
ftpService.closeFtpClient(ftpClient);
return Response.success("图片上传成功!", fileName);
} else {
ftpService.closeFtpClient(ftpClient);
return Response.fail("图片上传失败!");
}
} catch (IOException e) {
logger.error("图片上传异常", e);
return Response.fail("上传图片异常!");
} finally {
ftpService.closeFtpClient(ftpClient);
}
} else if ("0".equals(type)) {
fileUploadPath = diskcustomerFilePath + File.separator + customerId;
String newFileName = new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(new Date());
newFileName = newFileName.replace(" ", "");
newFileName = newFileName.replace(":", "");
fileName = newFileName + ".jpg";
} else if ("headPicture".equals(type)) {
fileUploadPath = headPictureSavePath + File.separator + customerId;
fileName = customerId + "_" + type + ".jpg";
} else if ("dbc_signature".equals(type) || "wmc_signature".equals(type)) {
fileUploadPath = creditSignature + File.separator + customerId;
fileName = customerId + "_" + type + ".jpg";
}

File savefolder = new File(fileUploadPath);
if (!savefolder.exists() && !savefolder.isDirectory()) {
savefolder.mkdirs();
}

String imgFilePath = fileUploadPath + File.separator + fileName;
logger.info(imgFilePath);
try {
out = new FileOutputStream(imgFilePath);
for (int i = 0; i < bytes.length; i++) { // 采用循环方式写入
out.write(bytes[i]);
}
} catch (FileNotFoundException e) {
logger.error("图片上传,找不到文件路径");
return Response.fail("图片上传,找不到文件路径!");
//throw new BusinessException("网络异常请稍后再试", e);
} catch (IOException e) {
e.printStackTrace();
logger.error("上传图片异常");
return Response.fail("上传图片异常");
} finally {
if (out != null) {
out.flush();
out.close();
}
}
return Response.success("图片上传成功!", fileName);
}

/**
* 检查是否已经上传了身份认证的三张照片
*
* @param paramMap 客户化id
*/
@POST
@Path("/checkIdentity")
public Response checkIdentityImages(Map<String, Object> paramMap) {
String customerId = CommonUtils.getValue(paramMap, "customerId");
if (StringUtils.isBlank(customerId)) {
return Response.fail("customerId不能为空");
}

//没有找到以customerId命名的文件,查询是否以openId命名
CustomerEntity customer = customerService.selectById(customerId);
if (customer == null) {
return Response.fail("该customerId对应的用户不存在");
}
String openId = customer.getOpenId();

// "front" "back" "similarity_person" "re_front" "re_similarity_person"
String[] type = {"front", "back", "similarity_person"};

boolean flag = false;
int i = -1;
try {
do {
//首先将数组下标自加1
i++; //
//得到文件路径
String fileName = customerId + "/" + customerId + "_" + type[i] + ".jpg";
//1.检查是否存在以customerId命名的文件
try {
logger.info("checkIdentityImages customerIdfile path:"+this.diskReadPath + fileName);
if (HttpClientUtils.getMethodGetContent(this.diskReadPath + fileName) != null) {
flag = true;
continue;
}
} catch (Exception e) {
logger.info("checkIdentityImages fail:"+e);
}
//2.当1的情况不存在时,检查是否存在以openId命名的文件
if (openId != null && !"null".equals(openId)) {
fileName = openId + "/" + openId + "_" + type[i] + ".jpg";
}

try {
logger.info("checkIdentityImages openIdfile path:"+this.diskReadPath + fileName);
if (HttpClientUtils.getMethodGetContent(diskReadPath+fileName)!=null) {
flag = true;
continue;
//没有找到以openID和customerId命名的文件,说明文件不存在
// return Response.fail("file is not exist");
} else {
//3.当1,2情况都不满足时,说明没有此类型文件,则表示缺少此类型图片
flag = false;
continue;
}
} catch (Exception e) {
logger.info("checkIdentityImages fail"+ e);
}

} while (flag && i < 2);
if (i >= 2) {
return Response.success("接口调用成功", "身份证认证照片检查成功");
}
} catch (Exception e) {
logger.info("身份证图片是否存在查询异常 ", e);
return Response.success("接口调用成功", "身份证认证照片检查成功");
}
return Response.fail("接口调用失败", "身份证认证照片检查状态:" + i);
}

/**
* 客户确认重新上传身份认证照片无误后,替换原来的
*/
@POST
@Path("/replaceNewIdentity")
public Response replaceNewIdentity(Map<String, Object> paramMap) {
FTPClient ftpClient=new FTPClient();
try {
String customerId = CommonUtils.getValue(paramMap, "customerId");
List<Object> types = CommonUtils.getListValue(paramMap, "type");
if (StringUtils.isBlank(customerId)) {
return Response.fail("客户编号不能为空");
}
ftpService.connect(ftpClient);
String rootPath = diskSavePath + customerId + "/";
FTPFile[] files = ftpService.listFiles(ftpClient,rootPath);
boolean flag = true;
int i;
for (i = 0; flag && i < types.size(); i++) {
String typeName = (String) types.get(i);
flag = false;
String newIdentityName = diskSavePath + customerId + "/"+ customerId + "_" + typeName + ".jpg";
if (ftpService.exists(ftpClient,newIdentityName) && ftpService.isFile(ftpClient,newIdentityName)) {
for (FTPFile file : files) {
String fileName = file.getName();
String oldType = fileName.substring(fileName.indexOf('_') + 1, fileName.indexOf('.'));
if (typeName.indexOf(oldType) > 0) {
boolean deleteFlag = ftpService.deleteFile(ftpClient,rootPath + fileName);
logger.info("delete oldIdentity file {} success:{} ", file.getName(), deleteFlag);
flag = ftpService.rename(ftpClient,newIdentityName, rootPath + fileName);
break;
}
}
if (!flag) {
logger.info("{} file replace fail.", newIdentityName);
}
}
}
ftpService.closeFtpClient(ftpClient);
if (flag && i >= 3) {
return Response.success("操作成功!");
} else {
return Response.fail("操作失败");
}
} catch (Exception e) {
logger.error("客户重新上传身份认证照片后进行替换操作失败" + e);
return Response.fail("操作失败,错误原因" + e);
}finally {
try {
ftpService.closeFtpClient(ftpClient);
} catch (IOException e) {
logger.error("ftp 关闭异常" + e);
}
}
}

}

ClientImageViewController的更多相关文章

随机推荐

  1. webstorm intelliJ IDEA phpstorm 设置鼠标滚动改变字体大小

    control+shift+A功能可以搜索对应功能,把mouse:Change font size(Zoom) ...的按钮打开,然后就可以通过 ctrl+鼠标上下滚动调节字体大小

  2. Javascript 函数声明、函数表达式与匿名函数自执行表达式

    函数表达式(Function Expression)注:将函数定义为表达式语句(通常是变量赋值)的一部分 //func() 错误 var func = function () { } //func() ...

  3. Android ANR的产生与分析

      ANR即Application Not Responding应用无响应,一般在ANR的时候会弹出一个应用无响应对话框.也许有些开发者在使用某些手机开发中不在弹出应用无响应弹出框,特别是国产手机An ...

  4. PHP为JSON数据的API返回空数组或者空对象

    在使用 JSON 作为 API 数据 Content-Type 的时候,会有这样一个问题: 如何返回一个空对象和一个空数组? 使用:json_encode(array())   得到JSON结果:[] ...

  5. PEP 492 -- Coroutines with async and await syntax 翻译

    因为工作中慢慢开始用python的协程,所以想更好的理解一下实现方式,故翻译此文 原文中把词汇表放到最后,但是我个人觉得放在最开始比较好,这样可以增加当你看原文时的理解程度 词汇表 原生协程函数 Na ...

  6. input 呼起数字键盘

    1. Android,定义 type="number" 2. iOS,定义 style="ime-mode: disabled;" 注,呼起数字键盘后,用户输入 ...

  7. py-faster-rcnn 训练参数修改(转)

    faster rcnn默认有三种网络模型 ZF(小).VGG_CNN_M_1024(中).VGG16 (大) 训练图片大小为500*500,类别数1. 一. 修改VGG_CNN_M_1024模型配置文 ...

  8. js 模仿jquery 写个简单的小demo

    <div id="div" style="background:red;width:100px;height:300px"> 123123123 & ...

  9. C# 3个延时函数

    ) { int time = Environment.TickCount; while (true) { if (Environment.TickCount - time >= DelayTim ...

  10. 乾坤合一~Linux设备驱动之终端设备驱动

    多想拥你在我的怀里 却无法超越那距离 美好回忆渐渐地远去 盼望今生出现奇迹 无尽的想念 荒了容颜 无助的爱恋 从未改变 这是今天的旋律,,,,今生今世,遥不可及~ 1 终端设备 终端是一种字符型设备, ...