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. MFC更换窗口图标

      https://blog.csdn.net/deep_kang/article/details/72722692: MFC更换图标,图像默认为MFC,主要步骤有三步. 第一步 找到一张图片(坑点: ...

  2. iOS Xcode 10: Multiple commands produce

    Xcode自动升级到10.0 1.编译的时候报错:Multiple commands produce 解决办法:File -> Workspace Setting -> build sys ...

  3. Effective Java 第三版——76. 争取保持失败原子性

    Tips 书中的源代码地址:https://github.com/jbloch/effective-java-3e-source-code 注意,书中的有些代码里方法是基于Java 9 API中的,所 ...

  4. IntelliJIdea 2016.2 使用 tomcat 8.5 调试spring的web项目时,bean被实例化两次导致timer和thread被启动了两遍的问题的解决

    今天新搭建了一个spring的web项目,项目启动时会启动一个线程,线程里定时执行任务,另外还启动了一个定时器,每秒钟统计系统吞吐量等业务性能数据.但是调试的时候惊奇的发现定时器和线程均被启动了两次. ...

  5. Session 在分布式系统中实现方式

    ##server独立Session 例如以下图所看到的: server独立Session要求用户的每次请求都必须在同一台应用server上面操作,这就要求负载均衡server每次都能把用户的请求发送到 ...

  6. macOS 下 PHPStorm + Xdebug 调试 Docker 环境中的代码

    0x00 描述 宿主机是 mac mini,构建的项目在 docker 中,所以需要在 PHPStorm 上配置 Xdebug 进行远程代码调试. 0x01 环境 宿主机:macOS High Sie ...

  7. idea checkout 项目

    1. 2.添加一个连接 选择远程目录checkout  , 然后选择本地目录   但是这样会创建一个新的projectwindow  如果要创建为module的话  1.手动引入从svn check的 ...

  8. C# Task中的Func, Action, Async与Await的使用

    在说Asnc和Await之前,先说明一下Func和Action委托, Task任务的基础的用法 1. Func Func是一种委托,这是在3.5里面新增的,2.0里面我们使用委托是用Delegate, ...

  9. Oracle sql 统计

    1.按小时统计数量 SELECT TO_CHAR(RECEIVE_TIME,'HH24') HOUR ,COUNT(*) N FROM PH_PRESCRIPTION P WHERE TO_CHAR( ...

  10. 【Unity】项目工程源码

    Unity开发者俱乐部 http://blog.csdn.net/dingxiaowei2013/article/details/50605208 游戏蛮牛 9秒社团 6m5m raywenderli ...