001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.usage;
018
019
020import org.apache.activemq.util.StoreUtil;
021
022import java.io.File;
023
024public abstract class PercentLimitUsage <T extends Usage> extends Usage<T> {
025
026    protected int percentLimit = 0;
027    protected long total = 0;
028
029    /**
030     * @param parent
031     * @param name
032     * @param portion
033     */
034    public PercentLimitUsage(T parent, String name, float portion) {
035        super(parent, name, portion);
036    }
037
038    public void setPercentLimit(int percentLimit) {
039        usageLock.writeLock().lock();
040        try {
041            this.percentLimit = percentLimit;
042            updateLimitBasedOnPercent();
043        } finally {
044            usageLock.writeLock().unlock();
045        }
046    }
047
048    public int getPercentLimit() {
049        usageLock.readLock().lock();
050        try {
051            return percentLimit;
052        } finally {
053            usageLock.readLock().unlock();
054        }
055    }
056
057    /**
058     * Sets the total available space in bytes. When non zero, the filesystem totalAvailableSpace is ignored.
059     * When set using Xbean, values of the form "20 Mb", "1024kb", and "1g" can be used
060     *
061     * @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.MemoryPropertyEditor"
062     */
063    public void setTotal(long max) {
064        this.total = max;
065    }
066
067    public long getTotal() {
068        return total;
069    }
070
071
072    protected void percentLimitFromFile(File directory) {
073        if (percentLimit > 0) {
074            if (total > 0) {
075                this.setLimit(total * percentLimit / 100);
076            } else if (directory != null) {
077                File dir = StoreUtil.findParentDirectory(directory);
078                if (dir != null) {
079                    this.setLimit(dir.getTotalSpace() * percentLimit / 100);
080                }
081            }
082        }
083    }
084
085    protected abstract void updateLimitBasedOnPercent();
086}