项目需求
用户定时需要收到指定的PDF 到邮箱 其中 PDF里必须是用户上次在前台选择过的图表类型
需求分析
- 首先需要去拿到用户自定义想要最近几天的数据(查询ES 这里需要去自己请求自己的接口拿到指定的数据)
- 去把数据渲染到echarts 只能纯后端生成 (echarts 需要跟前端选择的一样 所以这里需要跟前端调取一样的库)
- 把生成的echarts 的图片 通过流的形式添加到 PDF 文件中
- 在PDF 中加上指定的 文字以及 页脚
- 开始发送 email
- 修改JAVA 定时器 实现从数据库查的 cron 替换Springboot 本身自带的。
代码实现
模拟浏览器自己执行自己的接口
package com.ms.ssa.util.Post;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
@SuppressWarnings("resource")
public static String doPost(String url, String jsonstr, String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonstr);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result=EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
从ES 中查询数据
// 这里这个类是我封装的 请求数据的类
public void HttpGetData() throws Exception {
List<xxxxx> SendEmailList = ssaSendEmailService.GetAll();
SendEmailList.stream().forEach(s1 -> {
String name = s1.getName();
// 获取到你要发送给谁邮件
String to = s1.getTo();
// 邮件消息
String message = s1.getMessage();
// 邮件主题
String subject = s1.getSubject();
// 获取用户选择的 要几天内的数据
String time = s1.getTime();
String timeurl = "http://localhost:80/****/" + Integer.valueOf(time);
String httpOrgCreateTestRtn1 = HttpClientUtil.doPost(timeurl, "", "utf-8");
JSONObject parse = (JSONObject) JSONObject.parse(httpOrgCreateTestRtn1);
Object data = parse.get("data");
List<xxxx> SsaCountryReportList = ssaCustomReportService.GetAll1(name);
// url
SsaCountryReportList.stream().forEach(s -> {
// 获取图表类型
String Type = s.getName();
// 获取到用户 url
String url = s.getInterfaceName();
// 报表的 前 top
Integer top = s.getTop();
// ???????? count...
String explain = s.getExplain();
// searchWords 获取到用户 条件
String searchWords = s.getSearchWords();
// tle
String title = s.getTitle();
HashMap<String, Object> map = new HashMap<>();
map.put("top", top);
map.put("filterParam", searchWords + "&" + data);
// 根据条件去查询后端ES 的接口
String Dataurl = "http://localhost:80/api/api" + url;
String jsonStr = null;
try {
jsonStr = new ObjectMapper().writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String httpOrgCreateTestRtn = HttpClientUtil.doPost(Dataurl, jsonStr, "utf-8");
//System.out.println(httpOrgCreateTestRtn);
JSONObject parse1 = (JSONObject) JSONObject.parse(httpOrgCreateTestRtn);
if (!ObjectUtil.isEmpty((JSONObject) ((JSONObject) parse1.get("retData")).get("xxx"))) {
JSONObject infolists = (JSONObject) ((JSONObject) parse1.get("retData")).get("xxxx");
JSONArray jsonArray = infolists.getJSONArray(explain);
if (Type.equals(LINEONE)) {
SendEmail.HandleKVAndNV(Echart.lineOne(title), jsonArray, LINEONE);
} else if (Type.equals(LINETOW)) {
SendEmail.HandleKVAndNV(Echart.lineTwo(title), jsonArray, LINETOW);
} else if (Type.equals(BARONE)) {
SendEmail.HandleKVAndNV(Echart.BarOne(title), jsonArray, BARONE);
} else if (Type.equals(BARTWO)) {
SendEmail.HandleKVAndNV(Echart.BarTwo(title), jsonArray, BARTWO);
} else if (Type.equals(PIEONE)) {
SendEmail.HandleKVAndNV(Echart.PieOne(title), jsonArray, PIEONE);
} else if (Type.equals(PIETWI)) {
SendEmail.HandleKVAndNV(Echart.PieTwo(title), jsonArray, PIETWI);
}
}
});
// 拿到数据后去调用生成 PDF 的 方法
imagesToPdf("pdf 名称", System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/");
try {
// 调用发送 EMAIL 的方法
sendemail(to,subject,message);
} catch (Exception e) {
e.printStackTrace();
} finally {
String dataPath = System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/";
File file=new File(dataPath);
// 调用 删除 存放图片 方法 没次发完邮件清空图片的文件夹避免重复 发送
deleteFile(file);
}
});
}
生成 echarts 的代码
**这里需要自己安装phantomjs **
以及下面的js
package com.learn.echats;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.learn.echats.Mapper.SSa;
import com.learn.echats.echartutil.Echart;
import com.learn.echats.pojo.SsaCountryReport;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.ObjectUtils;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
@SpringBootTest
class EchatsApplicationTests {
private static final String JSpath = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\static\\echarts-convert.js";
// 定义常量
public static final String LINEONE = "lineOne";
public static final String LINETOW = "lineTwo";
public static final String BARONE = "BarOne";
public static final String BARTWO = "BarTwo";
public static final String PIEONE = "PieOne";
public static final String PIETWI = "PieTwo";
/**
* 这个是判断返回值类型是 kv name value
* Type :这个是图表的类型 就是 JSON option
* data 这个是数据库 查出来的数据
* name 这个是图表的name
*/
public static JSONObject HandleKVAndNV(String Type, String data, String name) {
// 第一种情况 是 line One
JSONObject optionsJson = (JSONObject) JSONObject.parse(Type);
// 定义 X 坐标
JSONArray xDataArray = new JSONArray();
// 这个是定义 Y 坐标
JSONArray yDataArray = new JSONArray();
// 饼图的
if (!ObjectUtils.isEmpty(data)) {
// 这里去判断 array 的数据到底是 k v 形式还是 name value 这里是我们数据格式 也可能不是这样
for (int i = 0; i < array.size(); ++i) {
JSONObject jsonObject = array.getJSONObject(i);
Object k = jsonObject.get("k");
if (!ObjectUtils.isEmpty(k)) {
xDataArray.add(jsonObject.get("k"));
yDataArray.add(jsonObject.get("v"));
} else {
xDataArray.add(jsonObject.get("name"));
yDataArray.add(jsonObject.get("value"));
}
}
}
if (name.equals(LINEONE)) {
JSONObject series = new JSONObject();
series.put("data", yDataArray);
series.put("type", "line");
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").add(series);
// 调用生成 图表的方法
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(LINETOW)) {
// JSONObject series = new JSONObject();
//series.put("data", yDataArray);
//series.put("type", "line");
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("type", "line");
// 调用生成 图表的方法
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(BARONE)) {
optionsJson.getJSONArray("xAxis").getJSONObject(0).put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("type", "bar");
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(BARTWO)) {
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
generateEChart(optionsJson.toJSONString());
}
else if (name.equals(PIEONE)) {
JSONArray dataArray = new JSONArray();
for (int i = 0; i < array.size(); ++i) {
JSONObject jsonObject = new JSONObject();
Object k = jsonObject.get("k");
jsonObject.put("name", array.getJSONObject(i).getString("k"));
jsonObject.put("value", array.getJSONObject(i).getString("v"));
dataArray.add(jsonObject);
}
optionsJson.getJSONArray("series").getJSONObject(0).put("data", dataArray);
generateEChart(optionsJson.toJSONString());
}
else if (name.equals(PIETWI)) {
JSONArray dataArray = new JSONArray();
for (int i = 0; i < array.size(); ++i) {
JSONObject jsonObject = new JSONObject();
Object k = jsonObject.get("k");
jsonObject.put("name", array.getJSONObject(i).getString("k"));
jsonObject.put("value", array.getJSONObject(i).getString("v"));
dataArray.add(jsonObject);
}
optionsJson.getJSONArray("series").getJSONObject(0).put("data", dataArray);
generateEChart(optionsJson.toJSONString());
}
return null;
}
/*
* 主程序
*/
public static String generateEChart(String options) {
String dataPath = writeFile(options);
// File file1 = new File("");
String fileName = UUID.randomUUID().toString() + ".png";
String path = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\Test\\" + fileName;
try {
File file = new File(path); //文件路径
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
String cmd = "C:\\Users\\86152\\Downloads\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;//生成命令行
System.out.println(cmd);
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.print(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return path;
}
/*
*
* options生成文件存储
*/
public static String writeFile(String options) {
String dataPath = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\Test\\" + UUID.randomUUID().toString().substring(0, 8) + ".json";
try {
/* option写入文本文件 用于执行命令*/
File writename = new File(dataPath);
if (!writename.exists()) {
File dir = new File(writename.getParent());
dir.mkdirs();
writename.createNewFile(); //
}
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
out.write(options);
out.flush(); // 把缓存区内容压入文件
out.close(); // 最后关闭文件
} catch (IOException e) {
e.printStackTrace();
}
return dataPath;
}
}
把图片写入到PDF
package com.learn.echats.Demo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.learn.echats.echartutil.PDFBuilder;
import java.io.File;
import java.io.FileOutputStream;
public class Demo {
private static String FILEPATH = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\Pdf\\";
/**
*
* @param fileName
* 生成pdf文件
* @param imagesPath
* 需要转换的图片路径的数组
*/
public static void imagesToPdf(String fileName, String imagesPath) {
try {
fileName = FILEPATH+fileName+".pdf";
File file = new File(fileName);
// 第一步:创建一个document对象。
Document document = new Document();
document.setMargins(20, 20, 60, 20);
// 第二步:
// 创建一个PdfWriter实例,
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
// 第三步:打开文档。
document.open();
// 第四步:在文档中增加图片。
File files = new File(imagesPath);
String[] images = files.list();
int len = images.length;
for (int i = 0; i < len; i++)
{
if (images[i].toLowerCase().endsWith(".bmp")
|| images[i].toLowerCase().endsWith(".jpg")
|| images[i].toLowerCase().endsWith(".jpeg")
|| images[i].toLowerCase().endsWith(".gif")
|| images[i].toLowerCase().endsWith(".png")) {
String temp = imagesPath + "\\" + images[i];
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
img.scalePercent(75);
// 根据图片大小设置页面,一定要先设置页面,再newPage(),否则无效
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
String path = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\fonts\\fangsong.ttf";
BaseFont bf = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 10f, Font.NORMAL, BaseColor.BLACK);
document.add(img);
// document.add(new Paragraph("SSA 报告分析", font));
}
}
builder.addPage(writer,document);
// 第五步:关闭文档。
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args)
{
String name = "20001543";
String imagesPath = "C:\\Users\\86152\\Desktop\\echarts-master\\echarts-master\\src\\main\\resources\\Test\\";
imagesToPdf(name, imagesPath);
}
}
PDF工具类用来写入页脚
package com.learn.echats.echartutil;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFBuilder extends PdfPageEventHelper {
/**
* 页眉
*/
public String header = "xxxx> 分析报告";
public String ye="页";
/**
* 文档字体大小,页脚页眉最好和文本大小一致
*/
public int presentFontSize = 13;
/**
* 文档页面大小,最好前面传入,否则默认为A4纸张
*/
public Rectangle pageSize = PageSize.A4;
// 模板
public PdfTemplate total;
// 基础字体对象
public BaseFont bf = null;
// 利用基础字体生成的字体对象,一般用于生成中文文字
public Font fontDetail = null;
/**
*
* Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
*
*/
public PDFBuilder() {
}
/**
*
* Creates a new instance of PdfReportM1HeaderFooter 构造方法.
*
* @param yeMei
* 页眉字符串
* @param presentFontSize
* 数据体字体大小
* @param pageSize
* 页面文档大小,A4,A5,A6横转翻转等Rectangle对象
*/
public PDFBuilder(String yeMei, int presentFontSize, Rectangle pageSize) {
this.header = yeMei;
this.presentFontSize = presentFontSize;
this.pageSize = pageSize;
}
public void setHeader(String header) {
this.header = header;
}
public void setPresentFontSize(int presentFontSize) {
this.presentFontSize = presentFontSize;
}
/**
*
* TODO 文档打开时创建模板
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(40, 45);// 共 页 的矩形的长宽高
}
/**
*
* TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
//this.addWatermark(writer);
}
//加分页
public void addPage(PdfWriter writer, Document document){
//设置分页页眉页脚字体
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 1.写入页眉
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase(header, fontDetail),
document.left(), document.top() + 20, 0);
// 2.写入前半部分的 第 X页/共
int pageS = writer.getPageNumber();
String foot1 = "第 " + pageS + ye+" /共";
Phrase footer = new Phrase(foot1, fontDetail);
// 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
float len = bf.getWidthPoint(foot1, presentFontSize);
// 4.拿到当前的PdfContentByte
PdfContentByte cb = writer.getDirectContent();
// 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
// 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
// ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
(document.rightMargin() + document.right()
+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
document.bottom() -7 , 0);
// 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
// len , y 轴和之前的保持一致,底边界-20
cb.addTemplate(total, (document.rightMargin() + document.right()
+ document.leftMargin() - document.left()) / 2.0F + 20F,
document.bottom() -7); // 调节模版显示的位置
}
//加水印
public void addWatermark(PdfWriter writer){
// 水印图片
Image image;
try {
image = Image.getInstance("./web/images/001.jpg");
PdfContentByte content = writer.getDirectContentUnder();
content.beginText();
// 开始写入水印
for(int k=0;k<5;k++){
for (int j = 0; j <4; j++) {
image.setAbsolutePosition(150*j,170*k);
content.addImage(image);
}
}
content.endText();
} catch (IOException | DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* TODO 关闭文档时,替换模板,完成整个页眉页脚组件
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onCloseDocument(PdfWriter writer, Document document) {
// 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
total.beginText();
total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
String foot2 = (writer.getPageNumber()) + ye; //页脚内容拼接 如 第1页/共2页
total.showText(foot2);// 模版显示的内容
total.endText();
total.closePath();
}
}
发送PDF 附件的邮箱
public void sendemail(String to,String subject,String message1) throws Exception{
//????
List<SsaEmailConfig> list = ssaEmailConfigService.list();
// ????????
String email_name = list.get(0).getEmail_name();
// ?????
String email_pwd = list.get(0).getEmail_pwd();
// // ????
String email_safe = list.get(0).getEmail_safe();
// // ?????
String email_host = list.get(0).getEmail_host();
// ??
String email_prot = list.get(0).getEmail_port();
Properties properties = new Properties();
properties.put("mail.smtp.auth", true);
properties.put("mail.smtp.connectiontimeout", 250000);
properties.put("mail.smtp.timeout", 250000);
properties.put("mail.smtp.writetimeout", 250000);
if (email_safe.equalsIgnoreCase(MAIL_OTHER_TYPE)) {
properties.put("mail.smtp.ssl.enable", true);
properties.put("mail.imap.ssl.socketFactory.fallback", false);
properties.put("mail.smtp.ssl.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (email_safe.equalsIgnoreCase(MAIL_MICROSOFT_TYPE)) {
properties.put("mail.smtp.starttls.enable", true);
properties.put("mail.smtp.starttls.required", true);
}
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(email_host);
javaMailSender.setPort(Integer.valueOf(email_prot));
javaMailSender.setUsername(email_name);
javaMailSender.setPassword(email_pwd);
javaMailSender.setJavaMailProperties(properties);
MimeMessage message = javaMailSender.createMimeMessage();
// MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
message.setFrom(email_name);
message.addRecipient(Message.RecipientType.TO, new InternetAddress((String) to));
message.setSubject((String) subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText((String) message1);
Multipart multipart = new MimeMultipart();
// ??????
multipart.addBodyPart(messageBodyPart);
// ????????
messageBodyPart = new MimeBodyPart();
// // // ?????PDF
// PdfConfig.base64StringToPDF((String) pdf,"/root/workspace/idea-workspace/src/main/resources/Demo.pdf");
//????????
String filename = System.getProperties().getProperty("user.dir") + "/src/main/resources/Pdf/SSA ????.pdf";
// pdf 的位置
String receiveName = "SSA ????.pdf";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
//messageBodyPart.setFileName(filename);
//???????????????????
messageBodyPart.setFileName(MimeUtility.encodeText(receiveName));
multipart.addBodyPart(messageBodyPart);
// ??????
message.setContent(multipart);
//????
message.saveChanges();
// ????
javaMailSender.send(message);
}
修改Springboot 自带的定时类
package com.example.demo.Demo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import java.util.Date;
import java.util.concurrent.Executors;
@Configuration
@EnableScheduling
public class scheduler1 implements SchedulingConfigurer {
// //添加定时任务
//定时任务1(2s执行一次)
//@Scheduled(cron = "0/2 * * * * ? ")
public void scheDuleTask() {
System.out.println("test"+Thread.currentThread());
}
//
// //定时任务2(5s执行一次)
// @Scheduled(cron = "0/5 * * * * ? ")
// public void scheDuleTask2() {
// System.out.println("test2"+Thread.currentThread());
// }
@Override
//每次执行完定时任务,都会重新执行一次configureTasks方法,根据参数重新设定定时器的执行时间
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//设定一个长度10的定时任务线程池
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> {
System.out.println("1");
scheDuleTask();
},
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
//这里的意思是数据库查出对应的cron属性
String cron = "0 */1 * * * ?";
//2.2 合法性校验.
if (StringUtils.isBlank(cron)) {
// Omitted Code ..
System.out.println("\"trackScheduler定时器的cron参数为空!!!!!\"");
// logger.info("trackScheduler定时器的cron参数为空!!!!!");
//如果为空则赋默认值
// cron = "0/5 * * * * ?";
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
//2.设置执行周期(Trigger)
);
}
}
整体代码
@Configuration
@EnableScheduling
public class SendEmail implements SchedulingConfigurer {
public static ISsaCustomReportService ssaCustomReportService;
@Autowired
public void setSsaCustomReportService(ISsaCustomReportService ssaCustomReportService) {
SendEmail.ssaCustomReportService = ssaCustomReportService;
}
public static SsaSendEmailService ssaSendEmailService;
@Autowired
public void setSsaSendEmailService(SsaSendEmailService ssaSendEmailService) {
SendEmail.ssaSendEmailService = ssaSendEmailService;
}
public static SsaEmailConfigService ssaEmailConfigService;
@Autowired
public void ssaEmailConfigService(SsaEmailConfigService ssaEmailConfigService) {
SendEmail.ssaEmailConfigService = ssaEmailConfigService;
}
public final String MAIL_OTHER_TYPE = "SSL";
public final String MAIL_MICROSOFT_TYPE = "TLS";
private static final String JSpath = System.getProperties().getProperty("user.dir") + "/src/main/resources/static/echarts-convert.js";
private static String FILEPATH = System.getProperties().getProperty("user.dir") + "/src/main/resources/Pdf/";
private static String cron = "";
// ????????
public static final String LINEONE = "lineOne";
public static final String LINETOW = "lineTwo";
public static final String BARONE = "BarOne";
public static final String BARTWO = "BarTwo";
public static final String PIEONE = "PieOne";
public static final String PIETWI = "PieTwo";
// ????
public void HttpGetData() throws Exception {
List<SsaSendEmail> SendEmailList = ssaSendEmailService.GetAll();
SendEmailList.stream().forEach(s1 -> {
String name = s1.getName();
String to = s1.getTo();
String message = s1.getMessage();
String subject = s1.getSubject();
String time = s1.getTime();
String timeurl = "http://localhost:80/api/api/CustomReport/interval/" + Integer.valueOf(time);
String httpOrgCreateTestRtn1 = HttpClientUtil.doPost(timeurl, "", "utf-8");
JSONObject parse = (JSONObject) JSONObject.parse(httpOrgCreateTestRtn1);
Object data = parse.get("data");
List<SsaCountryReport> SsaCountryReportList = ssaCustomReportService.GetAll1(name);
// url
SsaCountryReportList.stream().forEach(s -> {
// ????
String Type = s.getName();
// url
String url = s.getInterfaceName();
// top
Integer top = s.getTop();
// ???????? count...
String explain = s.getExplain();
// searchWords
String searchWords = s.getSearchWords();
// tle
String title = s.getTitle();
HashMap<String, Object> map = new HashMap<>();
map.put("top", top);
map.put("filterParam", searchWords + "&" + data);
String Dataurl = "http://localhost:80/api/api" + url;
String jsonStr = null;
try {
jsonStr = new ObjectMapper().writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String httpOrgCreateTestRtn = HttpClientUtil.doPost(Dataurl, jsonStr, "utf-8");
//System.out.println(httpOrgCreateTestRtn);
JSONObject parse1 = (JSONObject) JSONObject.parse(httpOrgCreateTestRtn);
if (!ObjectUtil.isEmpty((JSONObject) ((JSONObject) parse1.get("retData")).get("mapResult"))) {
JSONObject infolists = (JSONObject) ((JSONObject) parse1.get("retData")).get("mapResult");
JSONArray jsonArray = infolists.getJSONArray(explain);
if (Type.equals(LINEONE)) {
SendEmail.HandleKVAndNV(Echart.lineOne(title), jsonArray, LINEONE);
} else if (Type.equals(LINETOW)) {
SendEmail.HandleKVAndNV(Echart.lineTwo(title), jsonArray, LINETOW);
} else if (Type.equals(BARONE)) {
SendEmail.HandleKVAndNV(Echart.BarOne(title), jsonArray, BARONE);
} else if (Type.equals(BARTWO)) {
SendEmail.HandleKVAndNV(Echart.BarTwo(title), jsonArray, BARTWO);
} else if (Type.equals(PIEONE)) {
SendEmail.HandleKVAndNV(Echart.PieOne(title), jsonArray, PIEONE);
} else if (Type.equals(PIETWI)) {
SendEmail.HandleKVAndNV(Echart.PieTwo(title), jsonArray, PIETWI);
}
}
});
imagesToPdf("SSA ????", System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/");
try {
sendemail(to,subject,message);
} catch (Exception e) {
e.printStackTrace();
} finally {
String dataPath = System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/";
File file=new File(dataPath);//????
deleteFile(file);
}
});
}
private static void deleteFile(File file){
String[] childFilePath = file.list();
for (String path: childFilePath) {
File childFile= new File(file.getAbsoluteFile()+"/"+path);
if (childFile.isFile()) {
childFile.delete();
}
}
}
/**
* ?????????????????????? kv name value
* Type :????????????????
* data ???????????? ????????????
* explain ???????????????????????? count,down_traffic
* name ????????????name
*/
public static JSONObject HandleKVAndNV(String Type, JSONArray array, String name) {
// ?????????? ?? line One
JSONObject optionsJson = (JSONObject) JSONObject.parse(Type);
// ???? X ????
JSONArray xDataArray = new JSONArray();
// ?????????? Y ????
JSONArray yDataArray = new JSONArray();
// ??????
// ?????? Json ????
// ??????????
// ????????????????
if (!ObjectUtil.isEmpty(array)) {
// ?????????? array ???????????? k v ???????? name value
for (int i = 0; i < array.size(); ++i) {
JSONObject jsonObject = array.getJSONObject(i);
Object k = jsonObject.get("k");
if (!ObjectUtil.isEmpty(k)) {
xDataArray.add(jsonObject.get("k"));
yDataArray.add(jsonObject.get("v"));
} else {
xDataArray.add(jsonObject.get("name"));
yDataArray.add(jsonObject.get("value"));
}
}
}
if (name.equals(LINEONE)) {
JSONObject series = new JSONObject();
series.put("data", yDataArray);
series.put("type", "line");
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").add(series);
// ???????? ??????????
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(LINETOW)) {
// JSONObject series = new JSONObject();
//series.put("data", yDataArray);
//series.put("type", "line");
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("type", "line");
// ???????? ??????????
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(BARONE)) {
optionsJson.getJSONArray("xAxis").getJSONObject(0).put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("type", "bar");
generateEChart(optionsJson.toJSONString());
return optionsJson;
} else if (name.equals(BARTWO)) {
optionsJson.getJSONObject("xAxis").put("data", xDataArray);
optionsJson.getJSONArray("series").getJSONObject(0).put("data", yDataArray);
generateEChart(optionsJson.toJSONString());
} else if (name.equals(PIEONE)) {
JSONArray dataArray = new JSONArray();
for (int i = 0; i < array.size(); ++i) {
if (!ObjectUtil.isEmpty(array.getJSONObject(i).getString("k"))) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", array.getJSONObject(i).getString("k"));
jsonObject.put("value", array.getJSONObject(i).getString("v"));
dataArray.add(jsonObject);
}
else {
JSONObject jsonObject = new JSONObject();
String value = array.getJSONObject(i).getString("value");
String total = array.getJSONObject(i).getString("total");
Double vaue = (Double.valueOf(value) / Double.valueOf(total));
jsonObject.put("name", array.getJSONObject(i).getString("name"));
jsonObject.put("value", vaue);
// System.out.println(vaue);
dataArray.add(jsonObject);
}
}
optionsJson.getJSONArray("series").getJSONObject(0).put("data", dataArray);
generateEChart(optionsJson.toJSONString());
} else if (name.equals(PIETWI)) {
JSONArray dataArray = new JSONArray();
for (int i = 0; i < array.size(); ++i) {
System.out.println(array);
if (!ObjectUtil.isEmpty(array.getJSONObject(i).getString("k"))) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", array.getJSONObject(i).getString("k"));
jsonObject.put("value", array.getJSONObject(i).getString("v"));
dataArray.add(jsonObject);
}
else {
JSONObject jsonObject = new JSONObject();
String value = array.getJSONObject(i).getString("value");
String total = array.getJSONObject(i).getString("total");
Double vaue = (Double.valueOf(value) / Double.valueOf(total));
jsonObject.put("name", array.getJSONObject(i).getString("name"));
jsonObject.put("value", vaue);
// System.out.println(vaue);
dataArray.add(jsonObject);
}
}
optionsJson.getJSONArray("series").getJSONObject(0).put("data", dataArray);
generateEChart(optionsJson.toJSONString());
}
return null;
}
/*
* ??????
*/
public static String generateEChart(String options) {
String dataPath = writeFile(options);
// File file1 = new File("");
String fileName = UUID.randomUUID().toString() + ".png";
String path = System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/" + fileName;
try {
File file = new File(path); //????????
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
String cmd = "/usr/local/phantomjs/phantomjs-2.1.1-linux-x86_64/bin/phantomjs " + JSpath + " -infile " + dataPath + " -outfile " + path;//??????????
System.out.println(cmd);
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.print(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return path;
}
/*
*
* options????????????
*/
public static String writeFile(String options) {
;
String dataPath = System.getProperties().getProperty("user.dir") + "/src/main/resources/phg/" + UUID.randomUUID().toString().substring(0, 8) + ".json";
try {
/* option???????????? ????????????*/
File writename = new File(dataPath);
if (!writename.exists()) {
File dir = new File(writename.getParent());
dir.mkdirs();
writename.createNewFile(); //
}
BufferedWriter out = new BufferedWriter(new FileWriter(writename));
out.write(options);
out.flush(); // ????????????????????
out.close(); // ????????????
} catch (IOException e) {
e.printStackTrace();
}
return dataPath;
}
/**
* @param fileName ????pdf????
* @param imagesPath ????????????????????????
*/
public static void imagesToPdf(String fileName, String imagesPath) {
try {
fileName = FILEPATH + fileName + ".pdf";
File file = new File(fileName);
// ????????????????document??????
Document document = new Document();
document.setMargins(20, 20, 60, 20);
// ????????
// ????????PdfWriter??????
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
PDFBuilder builder = new PDFBuilder();
writer.setPageEvent(builder);
// ??????????????????
document.open();
// ??????????????????????????
File files = new File(imagesPath);
String[] images = files.list();
int len = images.length;
for (int i = 0; i < len; i++) {
if (images[i].toLowerCase().endsWith(".bmp")
|| images[i].toLowerCase().endsWith(".jpg")
|| images[i].toLowerCase().endsWith(".jpeg")
|| images[i].toLowerCase().endsWith(".gif")
|| images[i].toLowerCase().endsWith(".png")) {
String temp = imagesPath + images[i];
Image img = Image.getInstance(temp);
img.setAlignment(Image.ALIGN_CENTER);
img.scalePercent(75);
// ??????????????????????????????????????????newPage??????????????
document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
document.newPage();
document.add(img);
// document.add(new Paragraph("SSA ????????", font));
}
}
builder.addPage(writer, document);
// ??????????????????
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
//????????????????????????????????????configureTasks??????????????????????????????????????
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//????????????10????????????????
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
taskRegistrar.addTriggerTask(
//1.????????????(Runnable)
() -> {
try {
HttpGetData();
} catch (Exception e) {
e.printStackTrace();
}
},
//2.????????????(Trigger)
triggerContext -> {
//2.1 ????????????????????
//????????????????????????????cron????
List<SsaSendEmail> ssaSendEmails = ssaSendEmailService.GetAll();
ssaSendEmails.stream().forEach(ssaSendEmail -> {
cron = ssaSendEmail.getCron();
});
//2.2 ??????????.
if (StringUtils.isBlank(cron)) {
// Omitted Code ..
System.out.println("\"trackScheduler????????cron??????????????????\"");
// logger.info("trackScheduler????????cron??????????????????");
//??????????????????
cron = " 0 0 0 * * ? ";
}
//2.3 ????????????(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
//2.????????????(Trigger)
);
}
public void sendemail(String to,String subject,String message1) throws Exception{
//????
List<SsaEmailConfig> list = ssaEmailConfigService.list();
// ????????
String email_name = list.get(0).getEmail_name();
// ?????
String email_pwd = list.get(0).getEmail_pwd();
// // ????
String email_safe = list.get(0).getEmail_safe();
// // ?????
String email_host = list.get(0).getEmail_host();
// ??
String email_prot = list.get(0).getEmail_port();
Properties properties = new Properties();
properties.put("mail.smtp.auth", true);
properties.put("mail.smtp.connectiontimeout", 250000);
properties.put("mail.smtp.timeout", 250000);
properties.put("mail.smtp.writetimeout", 250000);
if (email_safe.equalsIgnoreCase(MAIL_OTHER_TYPE)) {
properties.put("mail.smtp.ssl.enable", true);
properties.put("mail.imap.ssl.socketFactory.fallback", false);
properties.put("mail.smtp.ssl.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
else if (email_safe.equalsIgnoreCase(MAIL_MICROSOFT_TYPE)) {
properties.put("mail.smtp.starttls.enable", true);
properties.put("mail.smtp.starttls.required", true);
}
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(email_host);
javaMailSender.setPort(Integer.valueOf(email_prot));
javaMailSender.setUsername(email_name);
javaMailSender.setPassword(email_pwd);
javaMailSender.setJavaMailProperties(properties);
MimeMessage message = javaMailSender.createMimeMessage();
// MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
message.setFrom(email_name);
message.addRecipient(Message.RecipientType.TO, new InternetAddress((String) to));
message.setSubject((String) subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText((String) message1);
Multipart multipart = new MimeMultipart();
// ??????
multipart.addBodyPart(messageBodyPart);
// ????????
messageBodyPart = new MimeBodyPart();
// // // ?????PDF
// PdfConfig.base64StringToPDF((String) pdf,"/root/workspace/idea-workspace/src/main/resources/Demo.pdf");
//????????
String filename = System.getProperties().getProperty("user.dir") + "/src/main/resources/Pdf/SSA ????.pdf";
//??????????? ??filename ????
String receiveName = "SSA ????.pdf";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
//messageBodyPart.setFileName(filename);
//???????????????????
messageBodyPart.setFileName(MimeUtility.encodeText(receiveName));
multipart.addBodyPart(messageBodyPart);
// ??????
message.setContent(multipart);
//????
message.saveChanges();
// ????
javaMailSender.send(message);
}
}