| /** |
| * |
| * 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 2.0 |
| * which accompanies this distribution, and is available at |
| * https://www.eclipse.org/legal/epl-2.0/ |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| * |
| * 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.StringToDoubleConverter; |
| |
| public class StringToFormattedDoubleConverter extends StringToDoubleConverter { |
| private static final long serialVersionUID = -4298862937719948986L; |
| 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(Double value, Class<? extends String> targetType, Locale locale) throws ConversionException { |
| if (value == null) { |
| return null; |
| } |
| |
| return getFormat(locale).format(value); |
| } |
| } |