| 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 | package org.springframework.batch.classify; |
| 17 | |
| 18 | import java.util.HashMap; |
| 19 | import java.util.Map; |
| 20 | |
| 21 | import org.springframework.batch.support.PatternMatcher; |
| 22 | |
| 23 | /** |
| 24 | * A {@link Classifier} that maps from String patterns with wildcards to a set |
| 25 | * of values of a given type. An input String is matched with the most specific |
| 26 | * pattern possible to the corresponding value in an input map. A default value |
| 27 | * should be specified with a pattern key of "*". |
| 28 | * |
| 29 | * @author Dave Syer |
| 30 | * |
| 31 | */ |
| 32 | public class PatternMatchingClassifier<T> implements Classifier<String, T> { |
| 33 | |
| 34 | private PatternMatcher<T> values; |
| 35 | |
| 36 | /** |
| 37 | * Default constructor. Use the setter or the other constructor to create a |
| 38 | * sensible classifier, otherwise all inputs will cause an exception. |
| 39 | */ |
| 40 | public PatternMatchingClassifier() { |
| 41 | this(new HashMap<String, T>()); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Create a classifier from the provided map. The keys are patterns, using |
| 46 | * '?' as a single character and '*' as multi-character wildcard. |
| 47 | * |
| 48 | * @param values |
| 49 | */ |
| 50 | public PatternMatchingClassifier(Map<String, T> values) { |
| 51 | super(); |
| 52 | this.values = new PatternMatcher<T>(values); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * A map from pattern to value |
| 57 | * @param values the pattern map to set |
| 58 | */ |
| 59 | public void setPatternMap(Map<String, T> values) { |
| 60 | this.values = new PatternMatcher<T>(values); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Classify the input by matching it against the patterns provided in |
| 65 | * {@link #setPatternMap(Map)}. The most specific pattern that matches will |
| 66 | * be used to locate a value. |
| 67 | * |
| 68 | * @return the value matching the most specific pattern possible |
| 69 | * |
| 70 | * @throws IllegalStateException if no matching value is found. |
| 71 | */ |
| 72 | public T classify(String classifiable) { |
| 73 | T value = values.match(classifiable); |
| 74 | return value; |
| 75 | } |
| 76 | |
| 77 | } |