001/*
002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
016 */
017
018package org.nuxeo.ecm.quota.size;
019
020import java.text.DecimalFormat;
021import java.text.NumberFormat;
022
023/**
024 * Helper class mainly used for UI display
025 * 
026 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
027 * @since 5.6
028 */
029public class QuotaDisplayValue {
030
031    protected static final long KB_LIMIT = 1024L;
032
033    protected static final long MB_LIMIT = 1024L * KB_LIMIT;
034
035    protected static final long GB_LIMIT = 1024L * MB_LIMIT;
036
037    public static final String GB_UNIT = "label.unit.GB";
038
039    public static final String MB_UNIT = "label.unit.MB";
040
041    public static final String KB_UNIT = "label.unit.KB";
042
043    public static final String UNLIMITED_VALUE = "label.unit.unlimited.value";
044
045    protected final long value;
046
047    protected float valueInUnit;
048
049    protected String unit;
050
051    protected long max;
052
053    public QuotaDisplayValue(long value) {
054        this.value = value;
055        init();
056    }
057
058    public QuotaDisplayValue(long value, long max) {
059        this(value);
060        this.max = max;
061    }
062
063    protected void init() {
064        if (value < 0) {
065            unit = UNLIMITED_VALUE;
066            valueInUnit = 0;
067        } else if (value > GB_LIMIT) {
068            unit = GB_UNIT;
069            valueInUnit = new Float(value) / GB_LIMIT;
070        } else if (value > MB_LIMIT) {
071            unit = MB_UNIT;
072            valueInUnit = new Float(value) / MB_LIMIT;
073        } else {
074            unit = KB_UNIT;
075            valueInUnit = new Float(value) / KB_LIMIT;
076        }
077    }
078
079    public long getValue() {
080        return value;
081    }
082
083    public float getValueInUnit() {
084        return valueInUnit;
085    }
086
087    public String getUnit() {
088        return unit;
089    }
090
091    public String getPercent() {
092        if (max > 0) {
093            NumberFormat formatter = new DecimalFormat("0.0");
094            return formatter.format((new Float(value) / max) * 100) + "%";
095        } else {
096            return "";
097        }
098    }
099}