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.io.File; 020import java.util.regex.Matcher; 021import java.util.regex.Pattern; 022 023/** 024 * Converts string values like "20 Mb", "1024kb", and "1g" to long or int values in bytes. 025 */ 026public final class XBeanByteConverterUtil { 027 028 private static final Pattern[] BYTE_MATCHERS = new Pattern[] { 029 Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$", Pattern.CASE_INSENSITIVE), 030 Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE), 031 Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE), 032 Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE)}; 033 034 private XBeanByteConverterUtil() { 035 // complete 036 } 037 038 public static Long convertToLongBytes(String str) throws IllegalArgumentException { 039 for (int i = 0; i < BYTE_MATCHERS.length; i++) { 040 Matcher matcher = BYTE_MATCHERS[i].matcher(str); 041 if (matcher.matches()) { 042 long value = Long.parseLong(matcher.group(1)); 043 for (int j = 1; j <= i; j++) { 044 value *= 1024; 045 } 046 return Long.valueOf(value); 047 } 048 } 049 throw new IllegalArgumentException("Could not convert to a memory size: " + str); 050 } 051 052 public static Integer convertToIntegerBytes(String str) throws IllegalArgumentException { 053 for (int i = 0; i < BYTE_MATCHERS.length; i++) { 054 Matcher matcher = BYTE_MATCHERS[i].matcher(str); 055 if (matcher.matches()) { 056 int value = Integer.parseInt(matcher.group(1)); 057 for (int j = 1; j <= i; j++) { 058 value *= 1024; 059 } 060 return Integer.valueOf(value); 061 } 062 } 063 throw new IllegalArgumentException("Could not convert to a memory size: " + str); 064 } 065 066}