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. iframe中video没有全屏按钮

    HTML内联框架元素 <iframe> iframe默认不允许全屏, 如果内嵌了video那么控制条上将不显示全屏按钮, 通过添加allowfullscreen属性可以开启全屏功能. mo ...

  2. js传递数组

    注意:数组不能直接作为参数传给后台,需要先用JSON处理成数组字符串,传到后台后再转回数组. var arr_str = JSON.stringify(array)

  3. mysql中实现字符串分割sp_split

      sp_split : DELIMITER $$ CREATE DEFINER = 'test_user'@'%' PROCEDURE sp_split (IN p_str varchar(2000 ...

  4. git ssh 22 端口不可用时通过https 443 端口配置git ssh

    Using SSH over the HTTPS port Sometimes, firewalls refuse to allow SSH connections entirely. If usin ...

  5. Linux Shell函数返回值

    转:http://blog.csdn.net/ithomer/article/details/7954577 Shell函数返回值,一般有3种方式:return,argv,echo 1) return ...

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

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

  7. BizTalk RosettaNet 开发笔记

    RNIF BAM Tracking Error  解决办法:  503: Service Unavailable   解决办法:IIS 应用程序池运行账户用户名或密码错误,用户名不能是doma ...

  8. Atitit r2017 r6 doc list on home ntpc.docx

    Atitit r2017 r6 doc list on home ntpc.docx 驱动器 D 中的卷是 p2soft 卷的序列号是 9AD0-D3C8 D:\ati\r2017 v4 raf\r2 ...

  9. java 查看SOAP请求报文

    log.info("ESB 请求URL = " + cachedEndpoint.toString());//打印SOAP请求报文 add by LinJC on 20170120 ...

  10. Canvas入门到高级详解(上)

    神奇的 canvas--AICODER 全栈培训 IT 培训专家 一.canvas 简介 1.1 什么是 canvas?(了解) 是 HTML5 提供的一种新标签 <canvas>< ...