SendOrderConfirmationEmailAdvice.java
Upload User: jiancairen
Upload Date: 2007-08-27
Package Size: 26458k
Code Size: 3k
Category:

Java Develop

Development Platform:

Java

  1. package org.springframework.samples.jpetstore.domain.logic;
  2. import java.lang.reflect.Method;
  3. import org.apache.commons.logging.Log;
  4. import org.apache.commons.logging.LogFactory;
  5. import org.springframework.aop.AfterReturningAdvice;
  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.mail.MailException;
  8. import org.springframework.mail.MailSender;
  9. import org.springframework.mail.SimpleMailMessage;
  10. import org.springframework.samples.jpetstore.domain.Account;
  11. import org.springframework.samples.jpetstore.domain.Order;
  12. /**
  13.  * AOP advice that sends confirmation email after order has been submitted
  14.  * @author Dmitriy Kopylenko
  15.  */
  16. public class SendOrderConfirmationEmailAdvice implements AfterReturningAdvice, InitializingBean {
  17. private static final String DEFAULT_MAIL_FROM = "jpetstore@springframework.org";
  18. private static final String DEFAULT_SUBJECT = "Thank you for your order!";
  19. private final Log logger = LogFactory.getLog(getClass());
  20. private MailSender mailSender;
  21. private String mailFrom = DEFAULT_MAIL_FROM;
  22. private String subject = DEFAULT_SUBJECT;
  23. public void setMailSender(MailSender mailSender) {
  24. this.mailSender = mailSender;
  25. }
  26. public void setMailFrom(String mailFrom) {
  27. this.mailFrom = mailFrom;
  28. }
  29. public void setSubject(String subject) {
  30. this.subject = subject;
  31. }
  32. public void afterPropertiesSet() throws Exception {
  33. if (this.mailSender == null) {
  34. throw new IllegalStateException("mailSender is required");
  35. }
  36. }
  37. public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable {
  38. Order order = (Order) args[0];
  39. Account account = ((PetStoreFacade) target).getAccount(order.getUsername());
  40. // don't do anything if email address is not set
  41. if (account.getEmail() == null || account.getEmail().length() == 0) {
  42. return;
  43. }
  44. StringBuffer text = new StringBuffer();
  45. text.append("Dear ").append(account.getFirstName()).append(' ').append(account.getLastName());
  46. text.append(", thank your for your order from JPetStore. Please note that your order number is ");
  47. text.append(order.getOrderId());
  48. SimpleMailMessage mailMessage = new SimpleMailMessage();
  49. mailMessage.setTo(account.getEmail());
  50. mailMessage.setFrom(this.mailFrom);
  51. mailMessage.setSubject(this.subject);
  52. mailMessage.setText(text.toString());
  53. try {
  54. this.mailSender.send(mailMessage);
  55. }
  56. catch (MailException ex) {
  57. // just log it and go on
  58. logger.warn("An exception occured when trying to send email", ex);
  59. }
  60. }
  61. }