View Javadoc

1   /*
2    * Copyright 2006-2010 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.springframework.batch.sample.domain.mail.internal;
17  
18  import java.util.ArrayList;
19  import java.util.LinkedHashMap;
20  import java.util.List;
21  import java.util.Map;
22  
23  import javax.mail.MessagingException;
24  
25  import org.springframework.mail.MailException;
26  import org.springframework.mail.MailSendException;
27  import org.springframework.mail.MailSender;
28  import org.springframework.mail.SimpleMailMessage;
29  
30  /**
31   * @author Dan Garrette
32   * @author Dave Syer
33   * 
34   * @since 2.1
35   */
36  public class TestMailSender implements MailSender {
37  
38  	private List<String> subjectsToFail = new ArrayList<String>();
39  
40  	private List<SimpleMailMessage> received = new ArrayList<SimpleMailMessage>();
41  
42  	public void clear() {
43  		received.clear();
44  	}
45  
46  	public void send(SimpleMailMessage simpleMessage) throws MailException {
47  		throw new UnsupportedOperationException("Not implememted.  Use send(SimpleMailMessage[]).");
48  	}
49  
50  	public void setSubjectsToFail(List<String> subjectsToFail) {
51  		this.subjectsToFail = subjectsToFail;
52  	}
53  
54  	public void send(SimpleMailMessage[] simpleMessages) throws MailException {
55  		Map<Object, Exception> failedMessages = new LinkedHashMap<Object, Exception>();
56  		for (SimpleMailMessage simpleMessage : simpleMessages) {
57  			if (subjectsToFail.contains(simpleMessage.getSubject())) {
58  				failedMessages.put(simpleMessage, new MessagingException());
59  			}
60  			else {
61  				received.add(simpleMessage);
62  			}
63  		}
64  		if (!failedMessages.isEmpty()) {
65  			throw new MailSendException(failedMessages);
66  		}
67  	}
68  
69  	public List<SimpleMailMessage> getReceivedMessages() {
70  		return received;
71  	}
72  
73  }