编写一个Groovy脚本,定期执行来生成业务报表。这个脚本主要完成三个动作:
1. 通过GroovySql从数据库中取出原始数据
2. 使用JfreeChart生成柱状图报表
3. 使用Apache的common-mail发送邮件
package com.cdai.gchart import groovy.sql.Sql import java.awt.Color import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.MultiPartEmail; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset import org.jfree.data.general.DatasetUtilities; class GChartRunner { /** * 报表数据 */ DefaultCategoryDataset dataset /** * 图片地址 */ static final def PIC_PATH = "test.png" static main(args) { new GChartRunner().run() } def run() { doLoadDataSet() doGenerateChart() doSendMail() } /** * 从数据库加载报表数据 * @return */ private def doLoadDataSet() { def sql = Sql.newInstance( "jdbc:mysql://127.0.0.1:3306/test", "root", "123456", "com.mysql.jdbc.Driver") dataset = new DefaultCategoryDataset(); sql.eachRow("select page_id, count(page_id) as pv " + "from page_traffic group by page_id") { dataset.addValue(it[1], it[0], ""); }; } /** * 创建3D柱状图图片文件 * @return */ private def doGenerateChart() { def chart = ChartFactory.createBarChart3D( "页面访问量统计", "页面ID", "访问量/次", dataset, PlotOrientation.VERTICAL, true, true, false) chart.setBackgroundPaint(Color.WHITE) ChartUtilities.writeChartAsPNG(new FileOutputStream(PIC_PATH), chart, 500, 500, true, 10) } /** * 将报表作为邮件附件发送 * @return */ private def doSendMail() { def email = new MultiPartEmail(); email.setHostName("smtp.163.com"); email.setAuthentication("[email protected]", "******"); email.setCharset("UTF-8"); email.addTo("[email protected]"); email.addTo("[email protected]"); email.setFrom("[email protected]", "cdai"); email.setSubject("页面访问量统计报告"); def attachment = new EmailAttachment(); attachment.setPath(PIC_PATH); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("页面访问量统计报告"); attachment.setName(PIC_PATH); email.attach(attachment); email.send(); } }
通过这个例子我们可以看到,强大的Groovy不仅与Java代码完美融合,并且通过语法糖及封装类库等方法,大大提高了生产力。
这在编写任务脚本等小功能时非常重要。
参考资料
实战 Groovy: 用 Groovy 进行 JDBC 编程
http://www.ibm.com/developerworks/cn/java/j-pg01115.html
JFreeChart: 基本柱状图
http://blog.csdn.net/originalcsdn/article/details/6215698
用Apache Commons Email简化邮件发送
http://www.blogjava.net/fastunit/archive/2008/01/25/177799.html