blob: 5615584a0030259ff16746c99dae7db2ab3b21d1 [file] [log] [blame]
/**
*
* Copyright (c) 2011, 2016 - Loetz GmbH&Co.KG (69115 Heidelberg, Germany)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
*
*/
package org.eclipse.osbp.utils.vaadin;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;
import java.util.Locale;
import org.apache.commons.lang.StringEscapeUtils;
import com.vaadin.data.util.converter.StringToBigDecimalConverter;
import com.vaadin.data.util.converter.StringToIntegerConverter;
public class StringToFormattedIntegerConverter extends StringToIntegerConverter {
/**
*
*/
private static final long serialVersionUID = -1587429363693818150L;
private PropertyLookup lookup = null;
private DecimalFormat decimalFormat = null;
public void setLookup(PropertyLookup lookup) {
this.lookup = lookup;
}
protected DecimalFormat getFormat(Locale locale) {
if (locale == null) {
if (lookup == null) {
locale = Locale.getDefault();
return (DecimalFormat) DecimalFormat.getInstance(locale);
} else {
locale = lookup.getLocale();
}
}
if (lookup == null || lookup.getFormat() == null) {
return (DecimalFormat) DecimalFormat.getInstance(locale);
}
try {
decimalFormat = new DecimalFormat(StringEscapeUtils.unescapeHtml(lookup.getFormat()), new DecimalFormatSymbols(locale));
} catch (IllegalArgumentException e){
String msg = String.format("formatter %s is invalid for decimal numbers: %s", lookup.getFormat(), e.getLocalizedMessage());
throw new ConversionException(msg);
}
return decimalFormat;
}
@Override
protected Number convertToNumber(String value, Class<? extends Number> targetType, Locale locale) throws ConversionException {
if (value == null) {
return null;
}
// Remove leading and trailing white space
value = value.trim();
// Parse and detect errors. If the full string was not used, it is
// an error.
ParsePosition parsePosition = new ParsePosition(0);
Number parsedValue = getFormat(locale).parse(value, parsePosition);
if (parsePosition.getIndex() != value.length()) {
throw new ConversionException("Could not convert '" + value
+ "' to " + getModelType().getName());
}
if (parsedValue == null) {
// Convert "" to null
return null;
}
return parsedValue;
}
@Override
public String convertToPresentation(Integer value, Class<? extends String> targetType, Locale locale) throws ConversionException {
if (value == null) {
return null;
}
return getFormat(locale).format(value);
}
}