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.file.transform; 018 019import java.util.Formatter; 020import java.util.Locale; 021 022import org.springframework.util.Assert; 023 024/** 025 * A {@link LineAggregator} implementation which produces a String by 026 * aggregating the provided item via the {@link Formatter} syntax.<br> 027 * 028 * @see Formatter 029 * 030 * @author Dave Syer 031 */ 032public class FormatterLineAggregator<T> extends ExtractorLineAggregator<T> { 033 034 private String format; 035 036 private Locale locale = Locale.getDefault(); 037 038 private int maximumLength = 0; 039 040 private int minimumLength = 0; 041 042 /** 043 * Public setter for the minimum length of the formatted string. If this is 044 * not set the default is to allow any length. 045 * 046 * @param minimumLength the minimum length to set 047 */ 048 public void setMinimumLength(int minimumLength) { 049 this.minimumLength = minimumLength; 050 } 051 052 /** 053 * Public setter for the maximum length of the formatted string. If this is 054 * not set the default is to allow any length. 055 * @param maximumLength the maximum length to set 056 */ 057 public void setMaximumLength(int maximumLength) { 058 this.maximumLength = maximumLength; 059 } 060 061 /** 062 * Set the format string used to aggregate items. 063 * 064 * @param format {@link String} containing the format to use. 065 * 066 * @see Formatter 067 */ 068 public void setFormat(String format) { 069 this.format = format; 070 } 071 072 /** 073 * Public setter for the locale. 074 * @param locale the locale to set 075 */ 076 public void setLocale(Locale locale) { 077 this.locale = locale; 078 } 079 080 @Override 081 protected String doAggregate(Object[] fields) { 082 083 Assert.notNull(format, "A format is required"); 084 085 String value = String.format(locale, format, fields); 086 087 if (maximumLength > 0) { 088 Assert.state(value.length() <= maximumLength, String.format("String overflowed in formatter -" 089 + " longer than %d characters: [%s", maximumLength, value)); 090 } 091 092 if (minimumLength > 0) { 093 Assert.state(value.length() >= minimumLength, String.format("String underflowed in formatter -" 094 + " shorter than %d characters: [%s", minimumLength, value)); 095 } 096 097 return value; 098 } 099}