001/*
002 * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
018 */
019
020package org.nuxeo.ecm.quota.size;
021
022import java.text.DecimalFormat;
023import java.text.NumberFormat;
024
025/**
026 * Helper class mainly used for UI display
027 * 
028 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
029 * @since 5.6
030 */
031public class QuotaDisplayValue {
032
033    protected static final long KB_LIMIT = 1024L;
034
035    protected static final long MB_LIMIT = 1024L * KB_LIMIT;
036
037    protected static final long GB_LIMIT = 1024L * MB_LIMIT;
038
039    public static final String GB_UNIT = "label.unit.GB";
040
041    public static final String MB_UNIT = "label.unit.MB";
042
043    public static final String KB_UNIT = "label.unit.KB";
044
045    public static final String UNLIMITED_VALUE = "label.unit.unlimited.value";
046
047    protected final long value;
048
049    protected float valueInUnit;
050
051    protected String unit;
052
053    protected long max;
054
055    public QuotaDisplayValue(long value) {
056        this.value = value;
057        init();
058    }
059
060    public QuotaDisplayValue(long value, long max) {
061        this(value);
062        this.max = max;
063    }
064
065    protected void init() {
066        if (value < 0) {
067            unit = UNLIMITED_VALUE;
068            valueInUnit = 0;
069        } else if (value > GB_LIMIT) {
070            unit = GB_UNIT;
071            valueInUnit = new Float(value) / GB_LIMIT;
072        } else if (value > MB_LIMIT) {
073            unit = MB_UNIT;
074            valueInUnit = new Float(value) / MB_LIMIT;
075        } else {
076            unit = KB_UNIT;
077            valueInUnit = new Float(value) / KB_LIMIT;
078        }
079    }
080
081    public long getValue() {
082        return value;
083    }
084
085    public float getValueInUnit() {
086        return valueInUnit;
087    }
088
089    public String getUnit() {
090        return unit;
091    }
092
093    public String getPercent() {
094        if (max > 0) {
095            NumberFormat formatter = new DecimalFormat("0.0");
096            return formatter.format((new Float(value) / max) * 100) + "%";
097        } else {
098            return "";
099        }
100    }
101}