Author: tchemit Date: 2014-04-08 18:24:07 +0200 (Tue, 08 Apr 2014) New Revision: 1867 Url: http://forge.codelutin.com/projects/wao/repository/revisions/1867 Log: improve import I18nAble parserFormatter Added: trunk/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/operations/I18nAbleParserFormatter.java Copied: trunk/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/operations/I18nAbleParserFormatter.java (from rev 1864, trunk/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/operations/LocalizedToStringParserFormatter.java) =================================================================== --- trunk/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/operations/I18nAbleParserFormatter.java (rev 0) +++ trunk/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/operations/I18nAbleParserFormatter.java 2014-04-08 16:24:07 UTC (rev 1867) @@ -0,0 +1,71 @@ +package fr.ifremer.wao.services.service.csv.operations; + +import com.google.common.collect.Sets; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.I18nAble; +import org.nuiton.csv.ValueParserFormatter; + +import java.text.ParseException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import static org.nuiton.i18n.I18n.l; + +/** + * Created on 4/8/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +public class I18nAbleParserFormatter<E extends I18nAble> implements ValueParserFormatter<E> { + + protected Map<E, String> toStrings = new HashMap<>(); + + protected Map<String, E> fromString = new HashMap<>(); + + protected final Locale locale; + + /** + * To parse null values (the formatted value will then be an empty string). + */ + protected boolean acceptNullValues; + + public void setAcceptNullValues(boolean acceptNullValues) { + this.acceptNullValues = acceptNullValues; + } + + @SafeVarargs + public I18nAbleParserFormatter(Locale locale, E... values) { + this(locale, Sets.newHashSet(values)); + } + + public I18nAbleParserFormatter(Locale locale, Collection<E> values) { + this.locale = locale; + for (E value : values) { + String valueToString = value == null ? "" : WaoUtils.l(locale, value); + toStrings.put(value, valueToString); + fromString.put(valueToString, value); + } + } + + @Override + public String format(E value) { + String valueAsString = toStrings.get(value); + if (!acceptNullValues && valueAsString == null) { + throw new IllegalArgumentException(); + } + return valueAsString; + } + + @Override + public E parse(String valueAsString) throws ParseException { + E value = fromString.get(valueAsString); + if (!acceptNullValues && value == null) { + String message = l(locale, "wao.import.failure.wrongValue", valueAsString, fromString.keySet().toString()); + throw new IllegalArgumentException(message); + } + return value; + } +}