KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > util > MemoryIntPropertyEditor


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.activemq.util;
19
20 import java.beans.PropertyEditorSupport JavaDoc;
21 import java.util.regex.Matcher JavaDoc;
22 import java.util.regex.Pattern JavaDoc;
23
24 /**
25  * Converts string values like "20 Mb", "1024kb", and "1g"
26  * to int values in bytes.
27  *
28  */

29 public class MemoryIntPropertyEditor extends PropertyEditorSupport JavaDoc {
30     public void setAsText(String JavaDoc text) throws IllegalArgumentException JavaDoc {
31
32         Pattern JavaDoc p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$",Pattern.CASE_INSENSITIVE);
33         Matcher JavaDoc m = p.matcher(text);
34         if (m.matches()) {
35             setValue(new Integer JavaDoc(Integer.parseInt(m.group(1))));
36             return;
37         }
38
39         p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$",Pattern.CASE_INSENSITIVE);
40         m = p.matcher(text);
41         if (m.matches()) {
42             setValue(new Integer JavaDoc(Integer.parseInt(m.group(1)) * 1024));
43             return;
44         }
45
46         p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE);
47         m = p.matcher(text);
48         if (m.matches()) {
49             setValue(new Integer JavaDoc(Integer.parseInt(m.group(1)) * 1024 * 1024 ));
50             return;
51         }
52
53         p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE);
54         m = p.matcher(text);
55         if (m.matches()) {
56             setValue(new Integer JavaDoc(Integer.parseInt(m.group(1)) * 1024 * 1024 * 1024 ));
57             return;
58         }
59
60         throw new IllegalArgumentException JavaDoc(
61                 "Could convert not to a memory size: " + text);
62     }
63
64     public String JavaDoc getAsText() {
65         Integer JavaDoc value = (Integer JavaDoc) getValue();
66         return (value != null ? value.toString() : "");
67     }
68
69 }
70
Popular Tags