001/* 002 * Copyright 2002-2013 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 005 * the License. You may obtain a copy of the License at 006 * 007 * https://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on 010 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 011 * specific language governing permissions and limitations under the License. 012 */ 013package org.springframework.batch.item; 014 015import java.util.List; 016 017import org.springframework.beans.factory.InitializingBean; 018import org.springframework.core.convert.converter.Converter; 019import org.springframework.util.Assert; 020 021/** 022 * A base class to implement any {@link ItemWriter} that writes to a key value store 023 * using a {@link Converter} to derive a key from an item 024 * 025 * @author David Turanski 026 * @since 2.2 027 * 028 */ 029public abstract class KeyValueItemWriter<K, V> implements ItemWriter<V>, InitializingBean { 030 031 protected Converter<V, K> itemKeyMapper; 032 protected boolean delete; 033 034 /* (non-Javadoc) 035 * @see org.springframework.batch.item.ItemWriter#write(java.util.List) 036 */ 037 @Override 038 public void write(List<? extends V> items) throws Exception { 039 if (items == null) { 040 return; 041 } 042 for (V item : items) { 043 K key = itemKeyMapper.convert(item); 044 writeKeyValue(key, item); 045 } 046 } 047 048 /** 049 * Subclasses implement this method to write each item to key value store 050 * @param key the key 051 * @param value the item 052 */ 053 protected abstract void writeKeyValue(K key, V value); 054 055 /** 056 * afterPropertiesSet() hook 057 */ 058 protected abstract void init(); 059 060 /** 061 * Set the {@link Converter} to use to derive the key from the item 062 * 063 * @param itemKeyMapper the {@link Converter} used to derive a key from an item. 064 */ 065 public void setItemKeyMapper(Converter<V, K> itemKeyMapper) { 066 this.itemKeyMapper = itemKeyMapper; 067 } 068 069 /** 070 * Sets the delete flag to have the item writer perform deletes 071 * 072 * @param delete if true {@link ItemWriter} will perform deletes, 073 * if false not to perform deletes. 074 */ 075 public void setDelete(boolean delete) { 076 this.delete = delete; 077 } 078 079 /* (non-Javadoc) 080 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() 081 */ 082 @Override 083 public void afterPropertiesSet() throws Exception { 084 Assert.notNull(itemKeyMapper, "itemKeyMapper requires a Converter type."); 085 init(); 086 } 087}