Commit 696c4a96 authored by 吴琼's avatar 吴琼

发送邮件

parent 6f24e5cd
...@@ -330,6 +330,10 @@ ...@@ -330,6 +330,10 @@
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.4.1</version> <version>5.4.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -10,6 +10,7 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; ...@@ -10,6 +10,7 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.scheduling.annotation.EnableAsync;
@Import(FdfsClientConfig.class) @Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
...@@ -17,6 +18,7 @@ import org.springframework.jmx.support.RegistrationPolicy; ...@@ -17,6 +18,7 @@ import org.springframework.jmx.support.RegistrationPolicy;
@ServletComponentScan @ServletComponentScan
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@EnableApolloConfig @EnableApolloConfig
@EnableAsync
@SpringBootApplication(scanBasePackages = {"cn.quantgroup.customer"}) @SpringBootApplication(scanBasePackages = {"cn.quantgroup.customer"})
public class Bootstrap { public class Bootstrap {
......
package cn.quantgroup.customer.config.mail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import java.util.Properties;
/**
* @author jie.feng
*/
@Configuration
public class MailConfig {
@Value("${customer.transaction.mail.from}")
private String username;
@Value("${customer.transaction.mail.host}")
private String host;
@Value("${customer.transaction.mail.port}")
private int port = 587;
@Value("${customer.transaction.mail.password}")
private String password;
@Bean(name = "monitorMailSender")
public JavaMailSender getSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setUsername(username);
javaMailSender.setHost(host);
javaMailSender.setPort(port);
javaMailSender.setDefaultEncoding("UTF-8");
javaMailSender.setPassword(password);
Properties prop = new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.timeout", "25000");
prop.setProperty("mail.smtp.port", Integer.toString(port));
//设置ssl端口
prop.setProperty("mail.smtp.socketFactory.port", Integer.toString(port));
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
javaMailSender.setJavaMailProperties(prop);
return javaMailSender;
}
}
\ No newline at end of file
...@@ -10,6 +10,7 @@ import com.alibaba.fastjson.JSONObject; ...@@ -10,6 +10,7 @@ import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import lombok.Synchronized; import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
...@@ -88,7 +89,13 @@ public class TransactionReceiptRecordRest { ...@@ -88,7 +89,13 @@ public class TransactionReceiptRecordRest {
@ResponseBody @ResponseBody
public JsonResult exportTransactionZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception{ public JsonResult exportTransactionZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
try{ try{
return transactionReceiptRecordService.exportZipFile(request,response); //transactionReceiptRecordService.deleteRedis("exportZipFile");
String str = transactionReceiptRecordService.checkRedis("exportZipFile");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("正在处理中,请稍后查看邮箱");
}
transactionReceiptRecordService.exportZipFile(request,response);
return JsonResult.buildSuccessResult("请求已发送,请稍后查看邮箱",null);
}catch(Exception e){ }catch(Exception e){
transactionReceiptRecordService.deleteRedis("exportZipFile"); transactionReceiptRecordService.deleteRedis("exportZipFile");
return JsonResult.buildErrorStateResult(e.getMessage()); return JsonResult.buildErrorStateResult(e.getMessage());
...@@ -96,10 +103,20 @@ public class TransactionReceiptRecordRest { ...@@ -96,10 +103,20 @@ public class TransactionReceiptRecordRest {
} }
@RequestMapping(value = "/redis", method = RequestMethod.GET) @RequestMapping(value = "/orderQuery/checkRedis", method = RequestMethod.GET)
public JsonResult redisTest() { public JsonResult redisTest(String type) {
transactionReceiptRecordService.deleteRedis("exportZipFile"); if(type.equals("1")){
return JsonResult.buildSuccessResult("删除成功",null); String str = transactionReceiptRecordService.checkRedis("importTransactionReceiptRecord");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("只能一个人导入,当前有其他人正在导入,请稍后重试");
}
}else{
String str = transactionReceiptRecordService.checkRedis("exportZipFile");
if(StringUtils.isNotBlank(str)){
return JsonResult.buildErrorStateResult("只能一个人导出,当前有其他人正在导出,请稍后重试");
}
}
return JsonResult.buildSuccessResult("ok",null);
} }
} }
package cn.quantgroup.customer.rest.param.mail;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.io.InputStreamSource;
import java.io.Serializable;
/**
* Desc :
* Date : 2017/9/28
* Created with suntao
*/
@Data
@NoArgsConstructor
public class SendMailParam implements Serializable {
private static final long serialVersionUID = -1L;
private String subject;
private String sender;
private String[] receiver;
private String[] copier;
private String contentText;
private String attachmentFileName;
private InputStreamSource inputStreamSource;
/**
* 简单邮件参数
* @param subject 主题
* @param sender 发件人
* @param receiver 收件人
* @param copier 抄送人
* @param contentText 内容
*/
public SendMailParam(String subject, String sender, String[] receiver, String[] copier, String contentText) {
this.subject = subject;
this.sender = sender;
this.receiver = receiver;
this.copier = copier;
this.contentText = contentText;
}
/**
* 附件邮件参数
* @param subject 主题
* @param sender 发件人
* @param receiver 收件人
* @param copier 抄送人
* @param contentText 内容
* @param attachmentFileName 附件名称
* @param inputStreamSource 附件流
*/
public SendMailParam(String subject, String sender, String[] receiver, String[] copier, String contentText, String attachmentFileName, InputStreamSource inputStreamSource) {
this.subject = subject;
this.sender = sender;
this.receiver = receiver;
this.copier = copier;
this.contentText = contentText;
this.attachmentFileName = attachmentFileName;
this.inputStreamSource = inputStreamSource;
}
}
...@@ -16,7 +16,7 @@ public interface ITransactionReceiptRecordService { ...@@ -16,7 +16,7 @@ public interface ITransactionReceiptRecordService {
JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException; JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException;
JsonResult exportZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception; void exportZipFile(HttpServletRequest request, HttpServletResponse response) throws Exception;
JsonResult checkCanExport(); JsonResult checkCanExport();
...@@ -26,4 +26,6 @@ public interface ITransactionReceiptRecordService { ...@@ -26,4 +26,6 @@ public interface ITransactionReceiptRecordService {
void deleteRedis(String str); void deleteRedis(String str);
String checkRedis(String str);
} }
...@@ -4,6 +4,7 @@ import cn.hutool.core.io.FileUtil; ...@@ -4,6 +4,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import cn.quantgroup.customer.entity.TransactionReceiptRecord; import cn.quantgroup.customer.entity.TransactionReceiptRecord;
import cn.quantgroup.customer.exception.BusinessException; import cn.quantgroup.customer.exception.BusinessException;
import cn.quantgroup.customer.rest.param.mail.SendMailParam;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptRecordVO; import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptRecordVO;
import cn.quantgroup.customer.repo.TransactionReceiptRecordRepo; import cn.quantgroup.customer.repo.TransactionReceiptRecordRepo;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery; import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
...@@ -11,10 +12,7 @@ import cn.quantgroup.customer.rest.vo.JsonResult; ...@@ -11,10 +12,7 @@ import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.*; import cn.quantgroup.customer.rest.vo.transaction.*;
import cn.quantgroup.customer.service.ITransactionReceiptRecordService; import cn.quantgroup.customer.service.ITransactionReceiptRecordService;
import cn.quantgroup.customer.service.http.IHttpService; import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.ExcelUtil; import cn.quantgroup.customer.util.*;
import cn.quantgroup.customer.util.FileToZip;
import cn.quantgroup.customer.util.ITextPDFUtil;
import cn.quantgroup.customer.util.SFTPUtil;
import cn.quantgroup.user.retbean.XUser; import cn.quantgroup.user.retbean.XUser;
import cn.quantgroup.user.vo.UserSysResult; import cn.quantgroup.user.vo.UserSysResult;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
...@@ -37,16 +35,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; ...@@ -37,16 +35,20 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.io.*; import java.io.*;
import java.math.BigDecimal;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
...@@ -95,6 +97,15 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -95,6 +97,15 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
@Value("${customer.transaction.local.file.limit}") @Value("${customer.transaction.local.file.limit}")
private int limit; private int limit;
//每次邮件可以接受的最大文件数
@Value("${customer.transaction.local.file.mailSize}")
private int mailSize;
@Value("${customer.transaction.mail.from}")
private String sender;
@Value("${customer.transaction.mail.url}")
private String receiver;
@Autowired @Autowired
private RedisTemplate<String, Object> redisTemplate; private RedisTemplate<String, Object> redisTemplate;
...@@ -146,7 +157,8 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -146,7 +157,8 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
/** /**
*校验是否有其他人在导入、导出 *校验是否有其他人在导入、导出
*/ */
private String checkRedis(String str){ @Override
public String checkRedis(String str){
log.info("redis add TransactionReceiptRecordServiceImpl."+str+".userId", redisTemplate); log.info("redis add TransactionReceiptRecordServiceImpl."+str+".userId", redisTemplate);
String obj = (String) redisTemplate.opsForValue().get("TransactionReceiptRecordServiceImpl."+str+".userId"); String obj = (String) redisTemplate.opsForValue().get("TransactionReceiptRecordServiceImpl."+str+".userId");
if(StringUtils.isBlank(obj)){ if(StringUtils.isBlank(obj)){
...@@ -313,11 +325,9 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -313,11 +325,9 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
//导出zip压缩包文件 //导出zip压缩包文件
@Transactional @Transactional
public JsonResult exportZipFile(HttpServletRequest request, HttpServletResponse response) throws RuntimeException { @Override
String str = checkRedis("exportZipFile"); @Async
if(StringUtils.isNotBlank(str)){ public void exportZipFile(HttpServletRequest request, HttpServletResponse response) throws RuntimeException {
throw new RuntimeException("只能一个人导出,当前有其他人正在导出,请稍后重试");
}
//调用电商接口获取对应数据 //调用电商接口获取对应数据
log.info("[TransactionReceiptRecordServiceImpl.exportZipFile begin]"); log.info("[TransactionReceiptRecordServiceImpl.exportZipFile begin]");
//查询需要导出的数据-导入成功的数据,但未导出成功的数据 //查询需要导出的数据-导入成功的数据,但未导出成功的数据
...@@ -325,14 +335,16 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -325,14 +335,16 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
log.info("[TransactionReceiptRecordServiceImpl.exportZipFile transactionReceiptRecordList] 可导出数据为:",transactionReceiptRecordList.size()); log.info("[TransactionReceiptRecordServiceImpl.exportZipFile transactionReceiptRecordList] 可导出数据为:",transactionReceiptRecordList.size());
if(CollectionUtils.isEmpty(transactionReceiptRecordList)){ if(CollectionUtils.isEmpty(transactionReceiptRecordList)){
deleteRedis("exportZipFile"); deleteRedis("exportZipFile");
return JsonResult.buildErrorStateResult("没有可以导出得数据"); log.info("没有可以导出得数据");
throw new RuntimeException("没有可以导出得数据");
} }
//查询导入成功数据的导出的最大批次号 //查询导入成功数据的导出的最大批次号
Integer maxExportBatchNo = transactionReceiptRecordRepo.findExportMaxBatchNo(1); Integer maxExportBatchNo = transactionReceiptRecordRepo.findExportMaxBatchNo(1);
if(maxExportBatchNo == null || maxExportBatchNo ==0 ){ if(maxExportBatchNo == null || maxExportBatchNo ==0 ){
maxExportBatchNo = 1; maxExportBatchNo = 1;
} }
List <Map<String,Object>> filePathList =new ArrayList<>();
List <Map<String,Object>> emailList =new ArrayList<>();
log.info("[TransactionReceiptRecordServiceImpl.kdspOperationUrl 调用kdsp-op 接口begin]", System.currentTimeMillis()); log.info("[TransactionReceiptRecordServiceImpl.kdspOperationUrl 调用kdsp-op 接口begin]", System.currentTimeMillis());
SFTPUtil sftpUtil = new SFTPUtil(username,password,host,port); SFTPUtil sftpUtil = new SFTPUtil(username,password,host,port);
sftpUtil.login(); sftpUtil.login();
...@@ -402,27 +414,101 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -402,27 +414,101 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
InputStream inputStream = new FileInputStream(file1); InputStream inputStream = new FileInputStream(file1);
sftpUtil.upload(basePath+maxExportBatchNo+"/交易凭证/",directory,pdfFileName,inputStream); sftpUtil.upload(basePath+maxExportBatchNo+"/交易凭证/",directory,pdfFileName,inputStream);
//将文件路径和useId放入list,进行签章 //将文件路径和useId放入list,进行签章
List <Map<String,Object>> filePathList =new ArrayList<>();
Map<String,Object> map =Maps.newHashMap(); Map<String,Object> map =Maps.newHashMap();
map.put("userId",record.getUserId()); map.put("userId",record.getUserId());
map.put("fileAddress",maxExportBatchNo+"/交易凭证/"+directory+"/"+pdfFileName); map.put("fileAddress",maxExportBatchNo+"/交易凭证/"+directory+"/"+pdfFileName);
log.info("需要签章得pdf路径:"+maxExportBatchNo+"/交易凭证/"+directory+"/"+pdfFileName); log.info("需要签章得pdf路径:"+maxExportBatchNo+"/交易凭证/"+directory+"/"+pdfFileName);
filePathList.add(map); filePathList.add(map);
//调用合同中心进行签章
restContract(filePathList,emailList);
} }
} catch (Exception e) { } catch (Exception e) {
deleteRedis("exportZipFile"); deleteRedis("exportZipFile");
log.error("[TransactionReceiptRecordServiceImpl][exportZipFile] 网络通讯异常,userId:{},ex:{}", ExceptionUtils.getStackTrace(e)); log.error("[TransactionReceiptRecordServiceImpl][exportZipFile] 网络通讯异常,userId:{},ex:{}", ExceptionUtils.getStackTrace(e));
return JsonResult.buildErrorStateResult(e.getMessage()); throw new RuntimeException("调用kdsp接口获取交易凭证订单信息报错");
} }
} }
sftpUtil.logout(); sftpUtil.logout();
log.info("uploadFile | 断开ftp"); log.info("uploadFile | 断开ftp");
log.info("[TransactionReceiptRecordServiceImpl.kdspOperationUrl 调用kdsp-op 接口end]",System.currentTimeMillis()); log.info("[TransactionReceiptRecordServiceImpl.kdspOperationUrl 调用kdsp-op 接口end]");
//调用签章接口
//将文件分批放入本地
log.info("下载签章完成的文件 begin");
int subListSize = 0;
if(CollectionUtils.isNotEmpty(emailList)){
List<List<Map<String,Object>>> subList= splitList(emailList,mailSize);
subListSize = subList.size();
for(int i =0;i<subList.size();i++){
List<Map<String,Object>>list =subList.get(i);
for(Map<String,Object> map:list){
String filePath = (String) map.get("filePath");
String fileName = (String) map.get("fileName");
SFTPUtil sftpUtil1 = new SFTPUtil(username,password,host,port);
sftpUtil1.login();
byte[] bytes = sftpUtil1.download(filePath,fileName);
String subPath = filePath.substring(0,filePath.length()-1);
int length2 = subPath.lastIndexOf("/");
String directory = subPath.substring(length2+1,subPath.length());
FileToZip.mkdir(downloadLocalPath+"/"+i+"/"+directory);
getFile(bytes,downloadLocalPath+"/"+i+"/"+directory,fileName);
sftpUtil1.logout();
}
}
}
log.info("下载签章完成的文件 end");
log.info("分批发送邮件 begin");
try {
for(int i=0;i<subListSize;i++){
File zipFile = ZipUtil.zip(downloadLocalPath+"\\"+i, downloadLocalPath+"\\"+i+".zip");
FileInputStream is = new FileInputStream(zipFile);
InputStreamResource InputStreamResource =new InputStreamResource(is);
sendCustomerTransactionMail(InputStreamResource);
}
log.info("分批发送邮件成功");
//return JsonResult.buildSuccessResult("ok",null);
} catch (Exception e) {
deleteRedis("exportZipFile");
throw new RuntimeException("邮件发送失败");
}
//File file = ZipUtil.zip(downloadLocalPath, downloadLocalPath+".zip");//zip 包保存路径
//FileInputStream is = null;
//try {
//is = new FileInputStream(file);
//byte[] fileData = new byte[is.available()];
//is.read(fileData);
//Map<String,Object> map = new HashMap<>();
//map.put("base64",Base64.getEncoder().encodeToString(fileData));
//int successCount = (int) jsonObject.get("successCount");
// int failCount = (int) jsonObject.get("failCount");
//map.put("successCount",successCount);
//map.put("failCount",failCount);
//删除生成的文件
//File deleteFile =new File("/home/quant_group/customer-service/tmp0/");
//deleteDirectory(deleteFile);
//File deleteFile1 =new File(downloadLocalPath);
// deleteDirectory(deleteFile1);
//deleteRedis("exportZipFile");
//return JsonResult.buildSuccessResult("ok",null);
//return JsonResult.buildSuccessResult("ok",map);
//} catch (Exception e) {
// deleteRedis("exportZipFile");
// throw new RuntimeException("文件转换失败");
// }
}
/**
* 调用签章接口
* @param filePathList
*/
private void restContract(List <Map<String,Object>> filePathList,List <Map<String,Object>> emailList){
log.info("contractUrl /contract/batch/sign 调用签章接口");
if(filePathList.isEmpty()){ if(filePathList.isEmpty()){
deleteRedis("exportZipFile"); deleteRedis("exportZipFile");
throw new RuntimeException("没有可以导出的数据"); throw new RuntimeException("没有可以导出的数据");
} }
log.info("contractUrl /contract/batch/sign 调用签章接口");
String url = contractUrl + "/contract/batch/sign"; String url = contractUrl + "/contract/batch/sign";
Map<String, String> header = Maps.newHashMap(); Map<String, String> header = Maps.newHashMap();
header.put("Content-type", "application/json"); header.put("Content-type", "application/json");
...@@ -437,31 +523,22 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -437,31 +523,22 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
throw new RuntimeException("签章失败!"); throw new RuntimeException("签章失败!");
} }
JSONObject jsonObject = JSONObject.parseObject(jsonResult); JSONObject jsonObject = JSONObject.parseObject(jsonResult);
JSONArray jsonArray = jsonObject.getJSONArray("successList"); JSONArray jsonArray = jsonObject.getJSONArray("successList");
log.info("contractUrl /contract/batch/sign jsonArray,"+jsonArray); log.info("contractUrl /contract/batch/sign jsonArray,"+jsonArray);
List<String> updateSuccessList = new ArrayList<>(); List<String> updateSuccessList = new ArrayList<>();
if(jsonArray != null && jsonArray.size()>0){ if(jsonArray != null && jsonArray.size()>0){
for(int i= 0;i <jsonArray.size() ;i++){ String path = (String) jsonArray.get(0);
String path = (String) jsonArray.get(i);
SFTPUtil sftpUtil1 = new SFTPUtil(username,password,host,port);
sftpUtil1.login();
String filepath = basePath + path.substring(1); String filepath = basePath + path.substring(1);
int totalLength =filepath.length(); int totalLength =filepath.length();
int length = filepath.lastIndexOf("/"); int length = filepath.lastIndexOf("/");
String fileName =filepath.substring(length+1,totalLength); String fileName =filepath.substring(length+1,totalLength);
updateSuccessList.add(fileName.substring(0,fileName.indexOf("."))); updateSuccessList.add(fileName.substring(0,fileName.indexOf(".")));
filepath =filepath.substring(0,length+1); filepath =filepath.substring(0,length+1);
byte[] bytes = sftpUtil1.download(filepath,fileName); Map<String,Object>map = Maps.newHashMap();
String subPath = filepath.substring(0,filepath.length()-1); map.put("filePath",filepath);
int length2 = subPath.lastIndexOf("/"); map.put("fileName",fileName);
String directory = subPath.substring(length2+1,subPath.length()); emailList.add(map);
FileToZip.mkdir(downloadLocalPath+"/"+directory);
getFile(bytes,downloadLocalPath+"/"+directory,fileName);
sftpUtil1.logout();
}
}else{ }else{
sftpUtil.logout();
deleteRedis("exportZipFile"); deleteRedis("exportZipFile");
throw new RuntimeException("签章失败!"); throw new RuntimeException("签章失败!");
} }
...@@ -471,42 +548,16 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -471,42 +548,16 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
log.info("contractUrl /contract/batch/sign failList,"+failList); log.info("contractUrl /contract/batch/sign failList,"+failList);
List<String> updateFailList = new ArrayList<>(); List<String> updateFailList = new ArrayList<>();
if(failList !=null && failList.size()>0){ if(failList !=null && failList.size()>0){
for(int i= 0;i <failList.size() ;i++){ String path = (String) failList.get(0);
String path = (String) failList.get(i);
int begin = path.lastIndexOf("/")+1; int begin = path.lastIndexOf("/")+1;
int end = path.indexOf("."); int end = path.indexOf(".");
path =path.substring(begin,end); path =path.substring(begin,end);
updateFailList.add(path); updateFailList.add(path);
} }
}
log.info("contractUrl /contract/batch/sign updateFailList,"+updateFailList);
//更新导出状态 //更新导出状态
log.info("交易凭证导出接口更新导出状态 begin"); log.info("交易凭证导出接口更新导出状态 begin");
updatePDFSignStatus(updateSuccessList,updateFailList); updatePDFSignStatus(updateSuccessList,updateFailList);
log.info("交易凭证导出接口更新导出状态 end"); log.info("交易凭证导出接口更新导出状态 end");
File file = ZipUtil.zip(downloadLocalPath, downloadLocalPath+".zip");//zip 包保存路径
FileInputStream is = null;
try {
is = new FileInputStream(file);
byte[] fileData = new byte[is.available()];
is.read(fileData);
Map<String,Object> map = new HashMap<>();
map.put("base64",Base64.getEncoder().encodeToString(fileData));
int successCount = (int) jsonObject.get("successCount");
int failCount = (int) jsonObject.get("failCount");
map.put("successCount",successCount);
map.put("failCount",failCount);
//删除生成的文件
File deleteFile =new File("/home/quant_group/customer-service/tmp0/");
deleteDirectory(deleteFile);
File deleteFile1 =new File(downloadLocalPath);
deleteDirectory(deleteFile1);
deleteRedis("exportZipFile");
return JsonResult.buildSuccessResult("ok",map);
} catch (Exception e) {
deleteRedis("exportZipFile");
throw new RuntimeException("文件转换失败");
}
} }
/** /**
...@@ -724,11 +775,11 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -724,11 +775,11 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
* @param groupSize * @param groupSize
* @return * @return
*/ */
private List<List<TransactionReceiptRecord>> splitList(List<TransactionReceiptRecord> records,int groupSize){ private List<List<Map<String,Object>>> splitList(List<Map<String,Object>> records,int groupSize){
int length = records.size(); int length = records.size();
//计算可以分为多少组 //计算可以分为多少组
int num = (length+groupSize-1)/groupSize; int num = (length+groupSize-1)/groupSize;
List<List<TransactionReceiptRecord>> newList = new ArrayList<>(); List<List<Map<String,Object>>> newList = new ArrayList<>();
for(int i= 0;i < num; i++){ for(int i= 0;i < num; i++){
//开始位置 //开始位置
int fromIndex = i * groupSize; int fromIndex = i * groupSize;
...@@ -964,4 +1015,25 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR ...@@ -964,4 +1015,25 @@ public class TransactionReceiptRecordServiceImpl implements ITransactionReceiptR
} }
return table; return table;
} }
public void sendCustomerTransactionMail(InputStreamResource inputStreamResource) throws Exception {
try {
//FileInputStream is = new FileInputStream("D:\\tmp1\\交易凭证.zip");
//InputStreamResource inputStreamResource1 =new InputStreamResource(is);
SendMailParam sendMailParam = new SendMailParam();
sendMailParam.setSender(sender);
sendMailParam.setReceiver(receiver.split(","));
sendMailParam.setSubject("交易凭证");
sendMailParam.setContentText("客服系统交易凭证文件");
sendMailParam.setAttachmentFileName("交易凭证".concat(".zip"));
sendMailParam.setInputStreamSource(inputStreamResource);
MailUtil.sendHtmlAndAttachmentMail(sendMailParam);
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("发送邮件失败");
}
}
} }
package cn.quantgroup.customer.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
*
* @author hang.zheng
*/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
@Autowired
public ApplicationContextHolder(ApplicationContext applicationContext) {
ApplicationContextHolder.applicationContext = applicationContext;
}
/**
* Spring应用上下文环境
*/
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境.
*
* @param applicationContext Spring ApplicationContext上下文
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
ApplicationContextHolder.applicationContext = applicationContext;
}
/**
* 获取一个ApplicationContext.
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 根据名称获取一个对象.
*
* @param name bean名称
* @return Object 指定的bean
* @throws BeansException 如果找不到bean
*/
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
/**
* 获取名称为name的bean,自动转为所需类型.
*
* @param <T> 需求的bean类型
* @param name bean名称
* @param requiredType 需求的bean类型
* @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型,或是类型不能被转换,或是bean实例化失败
*/
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
}
/**
* 获取类型为requiredType的对象.
*
* @param <T> 需求的bean类型
* @param requiredType 需求的bean类型
* @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型
*/
public static <T> T getBean(Class<T> requiredType) throws BeansException {
return applicationContext.getBean(requiredType);
}
/**
* 检测一个bean是否已经被定义.
*
* @param name bean名称
* @return boolean 如果bean已经被定义,则返回true,否则返回false
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype.
*
* @param name bean名称
* @return boolean 如果是singleton则返回true
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
/**
* 获取给定名字的bean的类型.
*
* @param name bean名称
* @return Class bean类型
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
/**
* 取出指定bean的别名列表.
*
* @param name bean名称
* @return 如果有别名,返回别名,否则返回空数组.
* @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
\ No newline at end of file
package cn.quantgroup.customer.util;
import cn.quantgroup.customer.rest.param.mail.SendMailParam;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import java.io.Serializable;
/**
* Date : 2017/9/28
* Created with suntao
*/
public class MailUtil implements Serializable {
private static final long serialVersionUID = -1L;
private static Logger logger = LoggerFactory.getLogger(MailUtil.class);
/**
* 发送一个简单邮件
*
* @param param
*/
public static void sendSampleMail(SendMailParam param) throws Exception {
if (!isSampleParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
//SimpleMailMessages实现了MimeMessageHelper,为普通邮件模板,支持文本。
SimpleMailMessage smm = new SimpleMailMessage();
// 设定邮件参数
smm.setFrom(param.getSender());
smm.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
smm.setCc(param.getCopier());
}
smm.setSubject(param.getSubject());
smm.setText(param.getContentText());
// 发送邮件
try {
mailSender.send(smm);
} catch (MailException e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
throw new Exception(e);
}
}
/**
* 发送一个支持html的邮件
*
* @param param Sender,Subject,Receiver,ContentText必选,Copier选填
*/
public static void sendHtmlMail(SendMailParam param) {
if (!isSampleParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
MimeMessage mimeMessage;
try {
mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(param.getSender());
helper.setSubject(param.getSubject());
helper.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
helper.setCc(param.getCopier());
}
helper.setText(param.getContentText(), Boolean.TRUE);
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
}
}
/**
* 发送一个支持html 和 附件 的邮件
*
* @param param Sender,Subject,Receiver,ContentText,AttachmentFileName,Attachment必选,Copier选填
*/
public static void sendHtmlAndAttachmentMail(SendMailParam param) {
if (!isAttachmentParamValidation(param)) {
return;
}
JavaMailSender mailSender = ApplicationContextHolder.getBean("monitorMailSender");
MimeMessage mimeMessage;
try {
mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(param.getSender());
helper.setSubject(param.getSubject());
helper.setTo(param.getReceiver());
if (ArrayUtils.isNotEmpty(param.getCopier())) {
helper.setCc(param.getCopier());
}
helper.setText(param.getContentText(), Boolean.TRUE);
helper.addAttachment(MimeUtility.encodeWord(param.getAttachmentFileName()), new ByteArrayResource(IOUtils.toByteArray(param.getInputStreamSource().getInputStream())));
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error("[MailUtilSendMail] 邮件发送失败。", e);
}
}
/**
* 验证简单邮件参数
*
* @param param
* @return true:参数正确;false:参数有误
*/
private static boolean isSampleParamValidation(SendMailParam param) {
if (param == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
return false;
}
if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText()) || ArrayUtils.isEmpty(param.getReceiver())) {
logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
return false;
}
return true;
}
/**
* 验证附件邮件参数
*
* @param param
* @return true:参数正确;false:参数有误
*/
private static boolean isAttachmentParamValidation(SendMailParam param) {
if (param == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 发送参数为空");
return false;
}
if (StringUtils.isAnyBlank(param.getSender(), param.getSubject(), param.getContentText(),
param.getAttachmentFileName()) || ArrayUtils.isEmpty(param.getReceiver()) || param.getInputStreamSource() == null) {
logger.error("[MailUtilSendMail] 邮件发送失败, 请检查参数");
return false;
}
return true;
}
}
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