PageRenderTime 54ms CodeModel.GetById 34ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 0ms

/protocols/smpp/src/main/java/org/mobicents/protocols/smpp/util/AbstractAPIConfig.java

http://mobicents.googlecode.com/
Java | 247 lines | 156 code | 19 blank | 72 comment | 26 complexity | 300d90df0420ba68504c31dca67245ad MD5 | raw file
  1/*
  2 * JBoss, Home of Professional Open Source
  3 * Copyright 2011, Red Hat, Inc. and individual contributors
  4 * by the @authors tag. See the copyright.txt in the distribution for a
  5 * full listing of individual contributors.
  6 *
  7 * This is free software; you can redistribute it and/or modify it
  8 * under the terms of the GNU Lesser General Public License as
  9 * published by the Free Software Foundation; either version 2.1 of
 10 * the License, or (at your option) any later version.
 11 *
 12 * This software is distributed in the hope that it will be useful,
 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 15 * Lesser General Public License for more details.
 16 *
 17 * You should have received a copy of the GNU Lesser General Public
 18 * License along with this software; if not, write to the Free
 19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 21 */
 22
 23package org.mobicents.protocols.smpp.util;
 24
 25import java.util.HashMap;
 26import java.util.Map;
 27
 28/**
 29 * Abstract base class for {@link APIConfig} instances. Provides some basic
 30 * functionality useful across all <tt>APIConfig</tt> instances.
 31 * <p>
 32 * <b>Boolean values:</b> Any of the strings "true", "on" or "yes" will
 33 * evaluate to a boolean <tt>true</tt>. The strings "false", "off" or "no"
 34 * will all evaluate to a boolean <tt>false</tt>. Additionally, booleans
 35 * can be numeric, where zero is evaluated as <tt>false</tt> and a non-zero
 36 * value is evaluated as <tt>true</tt>.
 37 * </p>
 38 * 
 39 * <p>
 40 * <b>Numbers</b>: Numbers can be specified in any of decimal, hexadecimal,
 41 * binary or octal notations. Decimal is the default. Prefixing a number
 42 * with "0x" causes it to be parsed as hexadecimal. Prefixing a number with
 43 * '0' causes it to be parsed as octal. Suffixing the number with a 'b'
 44 * causes it to be parsed as binary. For example:
 45 * </p>
 46 * <ul>
 47 * <li><tt>3757</tt> is a decimal number (base 10).</li>
 48 * <li><tt>0xa91</tt> is a hexadecimal number (base 16).</li>
 49 * <li><tt>0731</tt> is an octal number (base 8).</li>
 50 * <li><tt>1001110b</tt> is a binary number (base 2).</li>
 51 * </ul>
 52 * 
 53 * <p>
 54 * Decimal numbers may also be modified with a multiplier. Suffixing the
 55 * letters 'k' or 'm' at the end of a decimal number multiples it by
 56 * 1024 and 1048576 respectively. This is useful for specifying a number or
 57 * kilobytes or megabytes. For example
 58 * </p>
 59 * <ul>
 60 * <li><tt>4k</tt> is equivalent to <tt>4096</tt>.</li>
 61 * <li><tt>96m</tt> is equivalent to <tt>100663296</tt>.</li>
 62 * </ul>
 63 * @version $Id: AbstractAPIConfig.java 477 2009-07-12 18:00:20Z orank $
 64 */
 65public abstract class AbstractAPIConfig implements APIConfig {
 66    private static final Map<String, Boolean> BOOLEANS =
 67        new HashMap<String, Boolean>();
 68    
 69    static {
 70        BOOLEANS.put("1", Boolean.TRUE);
 71        BOOLEANS.put("true", Boolean.TRUE);
 72        BOOLEANS.put("on", Boolean.TRUE);
 73        BOOLEANS.put("yes", Boolean.TRUE);
 74        BOOLEANS.put("0", Boolean.FALSE);
 75        BOOLEANS.put("false", Boolean.FALSE);
 76        BOOLEANS.put("off", Boolean.FALSE);
 77        BOOLEANS.put("no", Boolean.FALSE);
 78    }
 79
 80    public boolean isSet(String property) {
 81        try {
 82            getProperty(property);
 83            return true;
 84        } catch (PropertyNotFoundException x) {
 85            return false;
 86        }
 87    }
 88    
 89    public String getProperty(String property, String defaultValue) {
 90        try {
 91            return getProperty(property);
 92        } catch (PropertyNotFoundException x) {
 93            return defaultValue;
 94        }
 95    }
 96
 97    public short getShort(String property) throws InvalidConfigurationException, PropertyNotFoundException {
 98        long value = getInt(property);
 99        if (value < (long) Short.MIN_VALUE || value > (long) Short.MAX_VALUE) {
100            throw new InvalidConfigurationException(
101                    "Property value exceeds valid short range: " + value, property);
102        }
103        return (short) value;
104    }
105    
106    public short getShort(String property, short defaultValue) {
107        short s;
108        try {
109            s = getShort(property);
110        } catch (PropertyNotFoundException x) {
111            s = defaultValue;
112        }
113        return s;
114    }
115
116    public int getInt(String property) throws InvalidConfigurationException, PropertyNotFoundException {
117        long value = convertToNumber(getProperty(property));
118        if (value < (long) Integer.MIN_VALUE || value > (long) Integer.MAX_VALUE) {
119            throw new InvalidConfigurationException(
120                    "Property value exceeds valid integer range: " + value,
121                    property);
122        }
123        return (int) value;
124    }
125    
126    public int getInt(String property, int defaultValue) {
127        int value;
128        try {
129            value = getInt(property);
130        } catch (PropertyNotFoundException x) {
131            value = defaultValue;
132        }
133        return value;
134    }
135
136    public long getLong(String property) throws InvalidConfigurationException, PropertyNotFoundException {
137        return convertToNumber(getProperty(property));
138    }
139    
140    public long getLong(String property, long defaultValue) {
141        long l;
142        try {
143            l = getLong(property);
144        } catch (PropertyNotFoundException x) {
145            l = defaultValue;
146        }
147        return l;
148    }
149
150    public boolean getBoolean(String property) throws InvalidConfigurationException, PropertyNotFoundException {
151        return toBoolean(getProperty(property));
152    }
153    
154    public boolean getBoolean(String property, boolean defaultValue) {
155        boolean value;
156        try {
157            value = getBoolean(property);
158        } catch (PropertyNotFoundException x) {
159            value = defaultValue;
160        }
161        return value;
162    }
163
164    public <T> T getClassInstance(String property, Class<T> type) {
165        String className = getProperty(property);
166        try {
167            Class<?> clazz = Class.forName(className);
168            if (!type.isAssignableFrom(clazz)) {
169                throw new InvalidConfigurationException(
170                        className + " is not an instance of " + type, className);
171            }
172            @SuppressWarnings("unchecked")
173            T obj = ((Class<T>) clazz).newInstance();
174            return obj;
175        } catch (Exception x) {
176            throw new InvalidConfigurationException(
177                    "Could not instantiate a " + className, x);
178        }
179    }
180    
181    public <T> T getClassInstance(String property, Class<T> type, T defaultValue) {
182        try {
183            return getClassInstance(property, type);
184        } catch (PropertyNotFoundException x) {
185            return defaultValue;
186        }
187    }
188    
189    /**
190     * Convert a string value to a boolean.
191     * @param value The value to determine a boolean value for.
192     * @return A boolean value.
193     * @throws InvalidConfigurationException If <tt>value</tt> is not
194     * a valid boolean value.
195     */
196    protected boolean toBoolean(String value) {
197        Boolean bool = BOOLEANS.get(value);
198        if (bool == null) {
199            try {
200                if (Integer.parseInt(value) != 0) {
201                    bool = Boolean.TRUE;
202                } else {
203                    bool = Boolean.FALSE;
204                }
205            } catch (NumberFormatException x) {
206                throw new InvalidConfigurationException(
207                        "Invalid boolean property", value);
208            }
209        }
210        return bool.booleanValue();
211    }
212
213    /**
214     * Convert a number string into a <code>long</code>, taking into account
215     * base and multiplication specifiers.
216     * @param num The String representing the number.
217     * @return The parsed number.
218     * @throws NumberFormatException If the String cannot be parsed as a number.
219     */
220    protected long convertToNumber(final String num) throws NumberFormatException {
221        int base = 10;
222        long multiplier = 1;
223        String s;
224        
225        char firstChar = num.charAt(0);
226        char lastChar = num.charAt(num.length() - 1);
227        if (num.startsWith("0x") || num.startsWith("0X")) {
228            base = 16;
229            s = num.substring(2);
230        } else if (lastChar == 'b') {
231            base = 2;
232            s = num.substring(0, num.length() - 1);
233        } else if (lastChar == 'k') {
234            multiplier = 1024L;
235            s = num.substring(0, num.length() - 1);
236        } else if (lastChar == 'm') {
237            multiplier = 1048576L;
238            s = num.substring(0, num.length() - 1);
239        } else if (firstChar == '0' && num.length() > 1) {
240            base = 8;
241            s = num.substring(1);
242        } else {
243            s = num;
244        }
245        return Long.parseLong(s, base) * multiplier;
246    }
247}