no.abmu.questionnaire.domain.data.BigDecimalFieldData.java Source code

Java tutorial

Introduction

Here is the source code for no.abmu.questionnaire.domain.data.BigDecimalFieldData.java

Source

/*$Id: BigDecimalFieldData.java 15424 2010-03-15 17:56:21Z jens $*/
/*
 ****************************************************************************
 *                                                                          *
 *                   (c) Copyright 2009 ABM-utvikling                       *
 *                                                                          *
 * 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 2 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. http://www.gnu.org/licenses/gpl.html    *
 *                                                                          *
 ****************************************************************************
 */

package no.abmu.questionnaire.domain.data;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import no.abmu.common.constants.LocaleTypeNameConst;
import no.abmu.questionnaire.domain.metadata.Field;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.springframework.binding.format.support.NumberFormatter;
import org.springframework.format.number.NumberFormatter;

/**
 * BigDecimalFieldData. 
 *
 * @author Aase Mestad
 * @author $Author: jens $
 * @version $Rev: 15424 $
 * @date $Date: 2010-03-15 18:56:21 +0100 (Mon, 15 Mar 2010) $
 * @copyright ABM-Utvikling
 */
@SuppressWarnings("serial")
@Entity
//@Table(name="BIGDECIMAL_FIELD_DATA", schema = DbSchemaNameConst.QUESTIONNAIRE_DB_SCHEMA_NAME)
//@PrimaryKeyJoinColumn(name="id")
@DiscriminatorValue("BigDecimal")
public class BigDecimalFieldData extends FieldDataImpl {

    /*
     * Implementation note: I'am currently not able to get propertyEditors to work together 
     * with WebFlow. So I'am setting and getting values as string.
     */

    private static final Log logger = (Log) LogFactory.getLog(BigDecimalFieldData.class);

    private int bigDecimalScale = 2;
    private BigDecimal bigDecimalValue;

    public BigDecimalFieldData() {
    }

    public BigDecimalFieldData(Field field) {
        super(field);
    }

    public BigDecimalFieldData(Field field, int bigDecimalScale) {
        super(field);
        this.bigDecimalScale = bigDecimalScale;
    }

    public BigDecimal getBigDecimalValue() {
        //        logger.debug("Executing getBigDecimalValue code=[" + getCode() 
        //        + "] bigDecimalValue=[" + bigDecimalValue + "]");
        return bigDecimalValue;
    }

    public void setBigDecimalValue(BigDecimal bigDecimal) {
        //        logger.debug("Executing setBigDecimalValue code=[" + getCode() + "] bigDecimalValue=[" + bigDecimal + "]");
        if (bigDecimal == null) {
            if (this.bigDecimalValue != null) {
                this.bigDecimalValue = null;
            }
            return;
        }
        if (bigDecimal.equals(this.bigDecimalValue)) {
            return;
        }
        this.bigDecimalValue = bigDecimal;
    }

    /*  ------   All the following method are transient.  ------  */

    @Transient
    public Object getUntypedValue() {
        //        logger.debug("Executing getUntypedValue.");
        return getValue();
    }

    @Transient
    public int getBigDecimalScale() {
        return bigDecimalScale;
    }

    @Transient
    public void setBigDecimalScale(int bigDecimalScale) {
        this.bigDecimalScale = bigDecimalScale;
    }

    @Transient
    public BigDecimal getValue() {
        //        logger.debug("Executing getValue code=[" + getCode() + "] bigDecimal=[" + bigDecimalValue + "]");
        return bigDecimalValue;
    }

    @Transient
    public void setValue(Object value) {
        //        logger.debug("Executing setValue as Object code=["  + getCode() + "] value=[" + value + "]");
        if (value == null) {
            if (this.bigDecimalValue != null) {
                this.bigDecimalValue = null;
            }
            return;
        }
        if (value instanceof BigDecimal) {
            setBigDecimalValue((BigDecimal) value);
            return;
        }
        if (value instanceof String) {
            String stringValue = (String) value;
            setValueAsString(stringValue);
            return;
        }

        logger.warn("Unknown dataType for " + this.toString() + " Code=[" + this.getCode()
                + "] DataType received was " + value.getClass().getName());

    }

    @Transient
    public void setValue(String value) {
        //        logger.debug("Executing setValue as String code=["  + getCode() + "] value=[" + value + "]");
        setValueAsString(value);
    }

    @Transient
    public void setValue(BigDecimal bigDecimal) {
        setBigDecimalValue(bigDecimal);
    }

    @Transient
    public boolean acceptValue(Object value) {
        return (value instanceof BigDecimal);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        BigDecimalFieldData that = (BigDecimalFieldData) o;

        if (bigDecimalValue != null ? !bigDecimalValue.equals(that.bigDecimalValue)
                : that.bigDecimalValue != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (bigDecimalValue != null ? bigDecimalValue.hashCode() : 0);
        return result;
    }

    /*  --------------------   Private methods.  --------------------------  */

    @Transient
    private String getValueAsString() {

        if (this.bigDecimalValue == null) {
            return null;
        }
        BigDecimal bigDecimalWithScaling = bigDecimalWithCorrectScaling(bigDecimalValue);
        double valueAsDouble = bigDecimalWithScaling.doubleValue();

        return getNumberFormat().format(valueAsDouble);
    }

    @Transient
    private void setValueAsString(String value) {
        //        logger.debug("Executing setValueAsString as String code=[" +  getCode() + "] value=[" + value + "]");
        if (value == null) {
            if (this.bigDecimalValue != null) {
                this.bigDecimalValue = null;
            }
            return;
        }
        String trimmedStringValue = value.trim();
        if (trimmedStringValue.isEmpty()) {
            if (this.bigDecimalValue != null) {
                this.bigDecimalValue = null;
            }
            return;
        }

        if (trimmedStringValue.contains(".")) {
            throw new NumberFormatException("Not valid number, use ',' not '.'");
        }

        DecimalFormat formatter = getNumberFormat();

        BigDecimal newBigDecimal;
        try {
            newBigDecimal = (BigDecimal) formatter.parse(trimmedStringValue);
        } catch (NumberFormatException e) {
            logger.error("Error on converting string value=[" + value + "]", e);
            throw new NumberFormatException(e.toString());
        } catch (ParseException e) {
            logger.error("Error on converting string value=[" + value + "]", e);
            throw new NumberFormatException(e.toString());
        }
        setBigDecimalValue(bigDecimalWithCorrectScaling(newBigDecimal));
    }

    @Transient
    private BigDecimal bigDecimalWithCorrectScaling(BigDecimal bigDecimal) {
        if (bigDecimal == null) {
            return null;
        }
        return bigDecimal.setScale(bigDecimalScale, BigDecimal.ROUND_UP);
    }

    @Transient
    private DecimalFormat getNumberFormat() {
        Locale locale = LocaleTypeNameConst.BOKMAAL;
        DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
        numberFormat.setMinimumFractionDigits(bigDecimalScale);
        numberFormat.setParseBigDecimal(true);
        return numberFormat;
    }
}