001/* Copyright (C) 2014 konik.io
002 *
003 * This file is part of the Konik library.
004 *
005 * The Konik library is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * The Konik library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with the Konik library. If not, see <http://www.gnu.org/licenses/>.
017 */
018package io.konik.jaxb.adapter;
019
020import io.konik.Configuration;
021
022import javax.xml.bind.annotation.adapters.XmlAdapter;
023import java.math.BigDecimal;
024import java.math.RoundingMode;
025
026import static java.lang.Integer.parseInt;
027import static java.math.RoundingMode.valueOf;
028
029/**
030 * 
031 * The Class MeasureRoundingAdapter.
032 */
033public class MeasureRoundingAdapter extends XmlAdapter<BigDecimal, BigDecimal> {
034
035   private static final String DEFAULT_ROUNDING_MODE = "HALF_UP";
036   private static final String DEFAULT_SCALE = "0";
037
038   final int scale;
039   final RoundingMode roundingMode;
040   private boolean stripTrailingZeros;
041
042   /**
043    * Instantiates a new amount rounding adapter.
044    */
045   public MeasureRoundingAdapter() {
046      String name = this.getClass().getName();
047      scale = parseInt(Configuration.INSTANCE.getProperty(name + ".scale", DEFAULT_SCALE));
048      roundingMode = valueOf(Configuration.INSTANCE.getProperty(name + ".roundingMode", DEFAULT_ROUNDING_MODE));
049      stripTrailingZeros = Configuration.INSTANCE.stripTrailingZeros();
050   }
051
052   @Override
053   public BigDecimal unmarshal(BigDecimal v) throws Exception {
054      return v;
055   }
056
057   @Override
058   public BigDecimal marshal(BigDecimal value) throws Exception {
059      if (value == null) { return null; }
060      BigDecimal roundedValue = value.setScale(scale, roundingMode);
061      if (stripTrailingZeros) { return roundedValue.stripTrailingZeros(); }
062      return roundedValue;
063   }
064}