001/* 002 * Copyright 2014 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 org.springframework.batch.item.ItemProcessor; 020import org.springframework.classify.Classifier; 021import org.springframework.classify.ClassifierSupport; 022 023/** 024 * Calls one of a collection of ItemProcessors, based on a router 025 * pattern implemented through the provided {@link Classifier}. 026 * 027 * Note the user is responsible for injecting a {@link Classifier} 028 * that returns an ItemProcessor that conforms to the declared input and output types. 029 * 030 * @author Jimmy Praet 031 * @since 3.0 032 */ 033public class ClassifierCompositeItemProcessor<I,O> implements ItemProcessor<I, O> { 034 035 private Classifier<? super I, ItemProcessor<?, ? extends O>> classifier = 036 new ClassifierSupport<I, ItemProcessor<?, ? extends O>> (null); 037 038 /** 039 * Establishes the classifier that will determine which {@link ItemProcessor} to use. 040 * @param classifier the {@link Classifier} to set 041 */ 042 public void setClassifier(Classifier<? super I, ItemProcessor<?, ? extends O>> classifier) { 043 this.classifier = classifier; 044 } 045 046 /** 047 * Delegates to injected {@link ItemProcessor} instances according to the 048 * classification by the {@link Classifier}. 049 */ 050 @Override 051 public O process(I item) throws Exception { 052 return processItem(classifier.classify(item), item); 053 } 054 055 /* 056 * Helper method to work around wildcard capture compiler error: see https://docs.oracle.com/javase/tutorial/java/generics/capture.html 057 * The method process(capture#4-of ?) in the type ItemProcessor<capture#4-of ?,capture#5-of ? extends O> is not applicable for the arguments (I) 058 */ 059 @SuppressWarnings("unchecked") 060 private <T> O processItem(ItemProcessor<T, ? extends O> processor, I input) throws Exception { 061 return processor.process((T) input); 062 } 063 064}