1 | /* |
2 | * Copyright 2006-2007 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 | |
17 | package org.springframework.batch.item.jms; |
18 | |
19 | import java.util.List; |
20 | |
21 | import org.apache.commons.logging.Log; |
22 | import org.apache.commons.logging.LogFactory; |
23 | import org.springframework.batch.item.ItemWriter; |
24 | import org.springframework.jms.core.JmsOperations; |
25 | import org.springframework.jms.core.JmsTemplate; |
26 | import org.springframework.util.Assert; |
27 | |
28 | /** |
29 | * An {@link ItemWriter} for JMS using a {@link JmsTemplate}. The template |
30 | * should have a default destination, which will be used to send items in |
31 | * {@link #write(List)}.<br/> |
32 | * <br/> |
33 | * |
34 | * The implementation is thread safe after its properties are set (normal |
35 | * singleton behavior). |
36 | * |
37 | * @author Dave Syer |
38 | * |
39 | */ |
40 | public class JmsItemWriter<T> implements ItemWriter<T> { |
41 | |
42 | protected Log logger = LogFactory.getLog(getClass()); |
43 | |
44 | private JmsOperations jmsTemplate; |
45 | |
46 | /** |
47 | * Setter for JMS template. |
48 | * |
49 | * @param jmsTemplate |
50 | * a {@link JmsOperations} instance |
51 | */ |
52 | public void setJmsTemplate(JmsOperations jmsTemplate) { |
53 | this.jmsTemplate = jmsTemplate; |
54 | if (jmsTemplate instanceof JmsTemplate) { |
55 | JmsTemplate template = (JmsTemplate) jmsTemplate; |
56 | Assert |
57 | .isTrue(template.getDefaultDestination() != null |
58 | || template.getDefaultDestinationName() != null, |
59 | "JmsTemplate must have a defaultDestination or defaultDestinationName!"); |
60 | } |
61 | } |
62 | |
63 | /** |
64 | * Send the items one-by-one to the default destination of the jms template. |
65 | * |
66 | * @see org.springframework.batch.item.ItemWriter#write(java.util.List) |
67 | */ |
68 | @Override |
69 | public void write(List<? extends T> items) throws Exception { |
70 | |
71 | if (logger.isDebugEnabled()) { |
72 | logger.debug("Writing to JMS with " + items.size() + " items."); |
73 | } |
74 | |
75 | for (T item : items) { |
76 | jmsTemplate.convertAndSend(item); |
77 | } |
78 | |
79 | } |
80 | |
81 | } |