spring定时器和spring javaMail

spring内置了定时器,其实是对java.util.timer的一个自己的实现。通过它可以定时的做一些任务,比如定时的发送邮件,同样的,spring对javaMail也进行了一些封装。看配置文件。

 

这个是配置文件mail.property

mail.username=xxxx
mail.password=xxxx
mail.host=mail.mchz.com.cn
[email protected]

mail.smtp.auth=true
mail.debug=true

resource=/xls
ipaddress=172.16.4.110
 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	 
	<import resource="applicationContext-propertyConfigurer.xml"/>
	
    
    <!-- 定时调度 -->
    <bean id="LoginAuditService" class="com.hzmc.capaa.business.search.impl.LoginAuditSendMailService">
    	<property name="from" value="${mail.from}"/>
    	<property name="resource" value="${resource}"/>
    	<property name="ipaddress" value="${ipaddress}"/>
    </bean>
    
     <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    	<property name="targetObject" ref="LoginAuditService"/>
    	<property name="targetMethod" value="sendLoginAuditMailReport"/>
    </bean>
           	
    <bean id="jobTiger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="jobDetail"/>
        <property name="cronExpression" value="0 45 8  * * ?"/>
    </bean>
          
	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="jobTiger"/>
			</list>
		</property>
		<property name="autoStartup" value="true"/>
	</bean>
	
	<!-- 邮件配置 -->
	<bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="${mail.host}"/>
		<property name="username" value="${mail.username}"/>
		<property name="password" value="${mail.password}"/>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
				<prop key="debug">${mail.debug}</prop>
			</props>
		</property>				
	</bean>
</beans>

 下面是业务类,负责发邮件的业务类。代码包含用jexcelAPI生成excel文件

package com.hzmc.capaa.business.search.impl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.WritableFont;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import com.hzmc.capaa.business.auditselect.AuditSelectManager;
import com.hzmc.capaa.business.search.LoginAuditSearchManager;
import com.hzmc.capaa.business.userconfig.UserConfigFileManager;
import com.hzmc.capaa.domain.persistence.audit.AuditSelect;
import com.hzmc.capaa.domain.persistence.search.LoginAuditSearch;
import com.hzmc.capaa.domain.persistence.userconfig.UserConfigFile;
import com.hzmc.capaa.web.util.GetCurrentDateTime;

public class LoginAuditSendMailService {

	@Autowired
	private JavaMailSender sender;

	@Autowired
	private UserConfigFileManager userConfigFileManger;

	@Autowired
	private LoginAuditSearchManager loginAuditSearchManager;

	@Autowired
	private AuditSelectManager auditSelectManager;

	private String from;
	
	private String ipaddress;
	
	private Resource resource;

	public void setFrom(String from) {
		this.from = from;
	}

	public void sendLoginAuditMailReport() {
		getCapaaUserList();
	}

	@SuppressWarnings("unchecked")
	public void getCapaaUserList() {
		List<UserConfigFile> userList = this.userConfigFileManger
				.getUserConfigFileList();
		for (UserConfigFile user : userList) {
			String name = user.getCapaaUser();
			String moudle = user.getAuditModule();
			String tomail = user.getUserEmail();
			String title = "您的关于登录审计的定制信息";
			String content = "你订阅的审计信息已经收到,请点击下面的链接下载或查看!\n";
			String[] moudles = moudle.split(";");
			for (String model : moudles) {
				if (model.indexOf("a") != -1) { //标示关注登录审计模块
					LoginAuditSearch loginAudit = this.loginAuditSearchManager
							.checkIsExists(name);
					if (loginAudit == null) {
						// 直接默认处理
						getLoginAuditDataList(name,"1=1",tomail,title,content);
					} else {
						// 加上默认的审计条件
						String dbUser=loginAudit.getDbUser();
						BigDecimal dbId=loginAudit.getDbId();
						String osUser=loginAudit.getOsUser();
						String realUser=loginAudit.getRealUser();
						String ipAddress=loginAudit.getIpAddress();
						String appName=loginAudit.getApplication();
						String timeStamp=loginAudit.getTimestamp();
						
						String whereFilter = "1=1";
						if (dbUser != null && !"".equals(dbUser)) {
							whereFilter += " and dbuser ='" + dbUser + "'";
						}

						if (dbId != null && !"".equals(dbId)) {
							whereFilter += " and dbid='" + dbId + "'";
						}
						if (osUser != null && !"".equals(osUser)) {
							whereFilter += " and osuser like '%" + osUser + "%'";
						}

						if (realUser != null && !"".equals(realUser)) {
							whereFilter += " and realuser like '%" + realUser + "%'";
						}
						if (ipAddress != null && !"".equals(ipAddress)) {
							whereFilter += " and IP_ADDRESS like '%" + ipAddress + "%'";
						}
						if (appName != null && !"".equals(appName)) {
							whereFilter += " and APP_NAME like '%" + appName + "%'";
						}
						if (timeStamp != null && !"".equals(timeStamp)) {
							whereFilter += " and TIMESTAMP >= to_date('" + timeStamp
									+ "','yyyy-mm-dd HH24:mi')";
						}
						
						getLoginAuditDataList(name,whereFilter,tomail,title,content);
						
					}
				}
			}

		}
	}

	@SuppressWarnings("unchecked")
	private void getLoginAuditDataList(String name,String whereFilter,String tomail,String title,String content) {
		Map map = new HashMap();
		map.put("ipAddress", whereFilter);
		map.put("dbId", new BigDecimal(0));
		map.put("countNumber", new Integer(200));
		map.put("clientId", UUID.randomUUID().toString());
		List<AuditSelect> list = this.auditSelectManager
				.getAuditSelectByPages(map);
		String fileName = name
				+ GetCurrentDateTime.getCurrentTime()+".xls";
		
		if (list != null) {
			try {
				if(!resource.getFile().getAbsoluteFile().exists()){
					File f=new File(resource.getFile().getAbsolutePath());
					f.mkdir();
				}
				extExcel(list, resource.getFile().getAbsolutePath()+"\\"+fileName);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		content="http://"+ipaddress+":8082/capaa/xls/"+fileName;
		sendMailtoCapaaUser(tomail,title,content);
	}

	@SuppressWarnings("unchecked")
	public void extExcel(List<AuditSelect> loginList, String fileName) {
		File file = new File(fileName);
		jxl.write.WritableWorkbook wwb = null;
		jxl.write.WritableSheet ws = null;
		try {
			file.createNewFile();
			wwb = Workbook.createWorkbook(file);
			ws = wwb.createSheet("LoginAuditSheet", 0);
			jxl.write.Label labela = new jxl.write.Label(0, 0, "数据库用户");
			jxl.write.Label labelb = new jxl.write.Label(1, 0, "IP地址");
			jxl.write.Label labelc = new jxl.write.Label(2, 0, "应用程序");
			jxl.write.Label labeld = new jxl.write.Label(3, 0, "登录时间");
			jxl.write.Label labele = new jxl.write.Label(4, 0, "响应行为");
			jxl.write.Label labelf = new jxl.write.Label(5, 0, "审计级别");
			jxl.write.Label labelg = new jxl.write.Label(6, 0, "错误性息");

			ws.addCell(labela);
			ws.addCell(labelb);
			ws.addCell(labelc);
			ws.addCell(labeld);
			ws.addCell(labele);
			ws.addCell(labelf);
			ws.addCell(labelg);
			
			for(int i=1;i<loginList.size()+1;i++){
				
				AuditSelect loginAudit=(AuditSelect)loginList.get(i-1);
				String dbUser = loginAudit.getDbUser();
				String ipAddress = loginAudit.getIpAddress();
				String appLication = loginAudit.getAppName();
				String loginTime = loginAudit.getTimestamp().toString();
				String reaction = loginAudit.getAuditClass();
				String auditLevel = loginAudit.getAuditLevel().toString();
				String errInfo = loginAudit.getErrMsg();
				
				
				jxl.write.Label lable1 = new jxl.write.Label(0, i, dbUser);
				jxl.write.Label lable2 = new jxl.write.Label(1, i, ipAddress);
				jxl.write.Label lable3 = new jxl.write.Label(2, i, appLication);
				jxl.write.Label lable4 = new jxl.write.Label(3, i, loginTime);
				jxl.write.Label lable5 = new jxl.write.Label(4, i, reaction);
				jxl.write.Label lable6 = new jxl.write.Label(5, i, auditLevel);
				jxl.write.Label lable7 = new jxl.write.Label(6, i, errInfo);
				
				ws.addCell(lable1);
				ws.addCell(lable2);
				ws.addCell(lable3);
				ws.addCell(lable4);
				ws.addCell(lable5);
				ws.addCell(lable6);
				ws.addCell(lable7);
				
				
			}

			jxl.write.WritableFont wfc = new jxl.write.WritableFont(
					WritableFont.ARIAL, 20, WritableFont.BOLD, false,
					UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.GREEN);

			jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
					wfc);

			wcfFC.setBackground(jxl.format.Colour.RED);
			wwb.write();
			wwb.close();
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	private void sendMailtoCapaaUser(String tomail, String title, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(tomail);
		message.setSubject(title);
		message.setText(content);
		sender.send(message);
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public void setIpaddress(String ipaddress) {
		this.ipaddress = ipaddress;
	}

}
 //假如是发送html邮件,那么用MimeMessage 
               MimeMessage msg = sender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
			
			helper.setFrom(from);
			helper.setTo(tomail);
			helper.setSubject(title);
			helper.setText(content,true);
			sender.send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		} 

你可能感兴趣的:(spring,AOP,bean,quartz,Excel)