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.file.transform;
18
19 import java.util.Formatter;
20 import java.util.Locale;
21
22 import org.springframework.util.Assert;
23
24 /**
25 * A {@link LineAggregator} implementation which produces a String by
26 * aggregating the provided item via the {@link Formatter} syntax.</br>
27 *
28 * @see Formatter
29 *
30 * @author Dave Syer
31 */
32 public class FormatterLineAggregator<T> extends ExtractorLineAggregator<T> {
33
34 private String format;
35
36 private Locale locale = Locale.getDefault();
37
38 private int maximumLength = 0;
39
40 private int minimumLength = 0;
41
42 /**
43 * Public setter for the minimum length of the formatted string. If this is
44 * not set the default is to allow any length.
45 *
46 * @param minimumLength the minimum length to set
47 */
48 public void setMinimumLength(int minimumLength) {
49 this.minimumLength = minimumLength;
50 }
51
52 /**
53 * Public setter for the maximum length of the formatted string. If this is
54 * not set the default is to allow any length.
55 * @param maximumLength the maximum length to set
56 */
57 public void setMaximumLength(int maximumLength) {
58 this.maximumLength = maximumLength;
59 }
60
61 /**
62 * Set the format string used to aggregate items.
63 *
64 * @see Formatter
65 */
66 public void setFormat(String format) {
67 this.format = format;
68 }
69
70 /**
71 * Public setter for the locale.
72 * @param locale the locale to set
73 */
74 public void setLocale(Locale locale) {
75 this.locale = locale;
76 }
77
78 @Override
79 protected String doAggregate(Object[] fields) {
80
81 Assert.notNull(format);
82
83 String value = String.format(locale, format, fields);
84
85 if (maximumLength > 0) {
86 Assert.state(value.length() <= maximumLength, String.format("String overflowed in formatter -"
87 + " longer than %d characters: [%s", maximumLength, value));
88 }
89
90 if (minimumLength > 0) {
91 Assert.state(value.length() >= minimumLength, String.format("String underflowed in formatter -"
92 + " shorter than %d characters: [%s", minimumLength, value));
93 }
94
95 return value;
96 }
97 }