View Javadoc

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.support;
18  
19  import java.util.ArrayList;
20  import java.util.HashMap;
21  import java.util.List;
22  import java.util.Map;
23  
24  import org.springframework.classify.Classifier;
25  import org.springframework.classify.ClassifierSupport;
26  import org.springframework.batch.item.ItemWriter;
27  
28  /**
29   * Calls one of a collection of ItemWriters for each item, based on a router
30   * pattern implemented through the provided {@link Classifier}.
31   * 
32   * The implementation is thread-safe if all delegates are thread-safe.
33   * 
34   * @author Dave Syer
35   * @since 2.0
36   */
37  public class ClassifierCompositeItemWriter<T> implements ItemWriter<T> {
38  
39  	private Classifier<T, ItemWriter<? super T>> classifier = new ClassifierSupport<T, ItemWriter<? super T>>(null);
40  
41  	/**
42  	 * @param classifier the classifier to set
43  	 */
44  	public void setClassifier(Classifier<T, ItemWriter<? super T>> classifier) {
45  		this.classifier = classifier;
46  	}
47  
48  	/**
49  	 * Delegates to injected {@link ItemWriter} instances according to their
50  	 * classification by the {@link Classifier}.
51  	 */
52      @Override
53  	public void write(List<? extends T> items) throws Exception {
54  
55  		Map<ItemWriter<? super T>, List<T>> map = new HashMap<ItemWriter<? super T>, List<T>>();
56  
57  		for (T item : items) {
58  			ItemWriter<? super T> key = classifier.classify(item);
59  			if (!map.containsKey(key)) {
60  				map.put(key, new ArrayList<T>());
61  			}
62  			map.get(key).add(item);
63  		}
64  
65  		for (ItemWriter<? super T> writer : map.keySet()) {
66  			writer.write(map.get(writer));
67  		}
68  
69  	}
70  
71  }