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 static java.lang.Integer.parseInt; 021import static java.math.RoundingMode.valueOf; 022import io.konik.Configuration; 023import io.konik.zugferd.unqualified.Amount; 024 025import java.math.BigDecimal; 026import java.math.RoundingMode; 027 028import javax.xml.bind.annotation.adapters.XmlAdapter; 029 030/** 031 * 032 * Adapter to round the amount during marshalling to two decimals after the period. 033 * 034 * The scale and rounding mode can be overridden via the configuration. 035 * 036 * Defaults:: 037 * 038 * ---- 039 * io.konik.jaxb.adapter.TwoDigitRoundingAdapter.scale=2 040 * io.konik.jaxb.adapter.TwoDigitRoundingAdapter.roundingMode=HALF_UP 041 * ---- 042 */ 043public class TwoDigitRoundingAdapter extends XmlAdapter<Amount, Amount> { 044 045 private static final String DEFAULT_SCALE = "2"; 046 private static final String DEFAULT_ROUNDING_MODE = "HALF_UP"; 047 048 private final int scale; 049 private final RoundingMode roundingMode; 050 private boolean stripTrailingZeros; 051 052 /** 053 * Instantiates a new amount rounding adapter. 054 */ 055 public TwoDigitRoundingAdapter() { 056 String name = this.getClass().getName(); 057 scale = parseInt(Configuration.INSTANCE.getProperty(name + ".scale", getDefaultScale())); 058 roundingMode = valueOf(Configuration.INSTANCE.getProperty(name + ".roundingMode", DEFAULT_ROUNDING_MODE)); 059 stripTrailingZeros = Configuration.INSTANCE.stripTrailingZeros(); 060 } 061 062 protected String getDefaultScale() { 063 return DEFAULT_SCALE; 064 } 065 066 @Override 067 public Amount unmarshal(Amount amount) throws Exception { 068 return amount; 069 } 070 071 @Override 072 public Amount marshal(Amount amount) throws Exception { 073 if (amount == null || amount.getValue() == null) { return amount; } 074 return amount.setValue(round(amount)); 075 } 076 077 private BigDecimal round(Amount amount) { 078 BigDecimal rounded = amount.getValue().setScale(scale, roundingMode); 079 if (stripTrailingZeros) { return rounded.stripTrailingZeros(); } 080 return rounded; 081 } 082}