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.support; 018 019import java.util.ArrayList; 020import java.util.LinkedHashMap; 021import java.util.List; 022import java.util.Map; 023 024import org.springframework.classify.Classifier; 025import org.springframework.classify.ClassifierSupport; 026import org.springframework.batch.item.ItemWriter; 027import org.springframework.util.Assert; 028 029/** 030 * Calls one of a collection of ItemWriters for each item, based on a router 031 * pattern implemented through the provided {@link Classifier}. 032 * 033 * The implementation is thread-safe if all delegates are thread-safe. 034 * 035 * @author Dave Syer 036 * @author Glenn Renfro 037 * @since 2.0 038 */ 039public class ClassifierCompositeItemWriter<T> implements ItemWriter<T> { 040 041 private Classifier<T, ItemWriter<? super T>> classifier = new ClassifierSupport<T, ItemWriter<? super T>>(null); 042 043 /** 044 * @param classifier the classifier to set 045 */ 046 public void setClassifier(Classifier<T, ItemWriter<? super T>> classifier) { 047 Assert.notNull(classifier, "A classifier is required."); 048 this.classifier = classifier; 049 } 050 051 /** 052 * Delegates to injected {@link ItemWriter} instances according to their 053 * classification by the {@link Classifier}. 054 */ 055 @Override 056 public void write(List<? extends T> items) throws Exception { 057 058 Map<ItemWriter<? super T>, List<T>> map = new LinkedHashMap<ItemWriter<? super T>, List<T>>(); 059 060 for (T item : items) { 061 ItemWriter<? super T> key = classifier.classify(item); 062 if (!map.containsKey(key)) { 063 map.put(key, new ArrayList<T>()); 064 } 065 map.get(key).add(item); 066 } 067 068 for (ItemWriter<? super T> writer : map.keySet()) { 069 writer.write(map.get(writer)); 070 } 071 072 } 073 074}