001/* 002 * Copyright 2006-2010 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.springframework.batch.sample.domain.mail.internal; 017 018import java.util.ArrayList; 019import java.util.LinkedHashMap; 020import java.util.List; 021import java.util.Map; 022 023import javax.mail.MessagingException; 024 025import org.springframework.mail.MailException; 026import org.springframework.mail.MailSendException; 027import org.springframework.mail.MailSender; 028import org.springframework.mail.SimpleMailMessage; 029 030/** 031 * @author Dan Garrette 032 * @author Dave Syer 033 * 034 * @since 2.1 035 */ 036public class TestMailSender implements MailSender { 037 038 private List<String> subjectsToFail = new ArrayList<>(); 039 040 private List<SimpleMailMessage> received = new ArrayList<>(); 041 042 public void clear() { 043 received.clear(); 044 } 045 046 @Override 047 public void send(SimpleMailMessage simpleMessage) throws MailException { 048 throw new UnsupportedOperationException("Not implemented. Use send(SimpleMailMessage[])."); 049 } 050 051 public void setSubjectsToFail(List<String> subjectsToFail) { 052 this.subjectsToFail = subjectsToFail; 053 } 054 055 @Override 056 public void send(SimpleMailMessage... simpleMessages) throws MailException { 057 Map<Object, Exception> failedMessages = new LinkedHashMap<>(); 058 for (SimpleMailMessage simpleMessage : simpleMessages) { 059 if (subjectsToFail.contains(simpleMessage.getSubject())) { 060 failedMessages.put(simpleMessage, new MessagingException()); 061 } 062 else { 063 received.add(simpleMessage); 064 } 065 } 066 if (!failedMessages.isEmpty()) { 067 throw new MailSendException(failedMessages); 068 } 069 } 070 071 public List<SimpleMailMessage> getReceivedMessages() { 072 return received; 073 } 074 075}