001/* 002 * Copyright 2006-2007 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 */ 016 017package org.springframework.batch.item.jms; 018 019import org.apache.commons.logging.Log; 020import org.apache.commons.logging.LogFactory; 021import org.springframework.batch.item.ItemWriter; 022import org.springframework.jms.core.JmsOperations; 023import org.springframework.jms.core.JmsTemplate; 024import org.springframework.util.Assert; 025 026import java.util.List; 027 028/** 029 * An {@link ItemWriter} for JMS using a {@link JmsTemplate}. The template 030 * should have a default destination, which will be used to send items in 031 * {@link #write(List)}.<br> 032 * <br> 033 * 034 * The implementation is thread-safe after its properties are set (normal 035 * singleton behavior). 036 * 037 * @author Dave Syer 038 * 039 */ 040public class JmsItemWriter<T> implements ItemWriter<T> { 041 042 protected Log logger = LogFactory.getLog(getClass()); 043 044 private JmsOperations jmsTemplate; 045 046 /** 047 * Setter for JMS template. 048 * 049 * @param jmsTemplate 050 * a {@link JmsOperations} instance 051 */ 052 public void setJmsTemplate(JmsOperations jmsTemplate) { 053 this.jmsTemplate = jmsTemplate; 054 if (jmsTemplate instanceof JmsTemplate) { 055 JmsTemplate template = (JmsTemplate) jmsTemplate; 056 Assert 057 .isTrue(template.getDefaultDestination() != null 058 || template.getDefaultDestinationName() != null, 059 "JmsTemplate must have a defaultDestination or defaultDestinationName!"); 060 } 061 } 062 063 /** 064 * Send the items one-by-one to the default destination of the JMS template. 065 * 066 * @see org.springframework.batch.item.ItemWriter#write(java.util.List) 067 */ 068 @Override 069 public void write(List<? extends T> items) throws Exception { 070 071 if (logger.isDebugEnabled()) { 072 logger.debug("Writing to JMS with " + items.size() + " items."); 073 } 074 075 for (T item : items) { 076 jmsTemplate.convertAndSend(item); 077 } 078 079 } 080 081}