fr.ird.observe.client.util.FloatConverter Maven / Gradle / Ivy
/*
* #%L
* ObServe Toolkit :: Common Client
* %%
* Copyright (C) 2008 - 2017 IRD, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* .
* #L%
*/
package fr.ird.observe.client.util;
import org.apache.commons.beanutils.ConversionException;
import org.nuiton.converter.NuitonConverter;
import static org.nuiton.i18n.I18n.t;
/**
* A float converter which is not dependant on user locale to obtain the locale
* {@code dot} representation.
*
* It can transform {@code 0.2} and also {@code 0, 2}.
*
* @author tchemit - [email protected]
* @since 1.3
*/
public class FloatConverter implements NuitonConverter {
@Override
public Object convert(Class aClass, Object value) {
if (value == null) {
throw new ConversionException(t("observe.converter.error.noValue", this));
}
if (isEnabled(aClass)) {
Object result;
if (isEnabled(value.getClass())) {
result = value;
return result;
}
if (value instanceof String) {
result = valueOf((String) value);
return result;
}
}
throw new ConversionException(t("observe.converter.error.no.convertor", value, aClass.getName()));
}
protected Float valueOf(String value) {
try {
if (value.contains(",")) {
value = value.replaceAll(",", ".");
}
Float result;
result = Float.valueOf(value);
return result;
} catch (NumberFormatException e) {
throw new ConversionException(t("observe.converter.error.float.format", value, this, e.getMessage()));
}
}
protected boolean isEnabled(Class> aClass) {
return Float.class.equals(aClass);
}
@Override
public Class getType() {
return Float.class;
}
}