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.util;
018
019import java.beans.PropertyEditorSupport;
020import java.util.regex.Matcher;
021import java.util.regex.Pattern;
022
023/**
024 * Converts string values like "20 Mb", "1024kb", and "1g" to long values in
025 * bytes.
026 */
027public class MemoryPropertyEditor extends PropertyEditorSupport {
028    public void setAsText(String text) throws IllegalArgumentException {
029
030        Pattern p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$", Pattern.CASE_INSENSITIVE);
031        Matcher m = p.matcher(text);
032        if (m.matches()) {
033            setValue(Long.valueOf(Long.parseLong(m.group(1))));
034            return;
035        }
036
037        p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE);
038        m = p.matcher(text);
039        if (m.matches()) {
040            setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024));
041            return;
042        }
043
044        p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE);
045        m = p.matcher(text);
046        if (m.matches()) {
047            setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024));
048            return;
049        }
050
051        p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE);
052        m = p.matcher(text);
053        if (m.matches()) {
054            setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024 * 1024));
055            return;
056        }
057
058        throw new IllegalArgumentException("Could convert not to a memory size: " + text);
059    }
060
061    public String getAsText() {
062        Long value = (Long)getValue();
063        return value != null ? value.toString() : "";
064    }
065
066}