Example usage for java.lang NumberFormatException NumberFormatException

List of usage examples for java.lang NumberFormatException NumberFormatException

Introduction

In this page you can find the example usage for java.lang NumberFormatException NumberFormatException.

Prototype

public NumberFormatException(String s) 

Source Link

Document

Constructs a NumberFormatException with the specified detail message.

Usage

From source file:org.occiware.mart.server.servlet.utils.Utils.java

/**
 * Parse a string to a number without knowning its type output.
 *
 * @param str/* w ww.j ava2 s  .co  m*/
 * @param instanceClassType can be null.
 * @return a non null number object.
 */
public static Number parseNumber(String str, String instanceClassType) {
    Number number;
    if (instanceClassType == null) {

        try {
            number = Float.parseFloat(str);

        } catch (NumberFormatException e) {
            try {
                number = Double.parseDouble(str);
            } catch (NumberFormatException e1) {
                try {
                    number = Integer.parseInt(str);
                } catch (NumberFormatException e2) {
                    try {
                        number = Long.parseLong(str);
                    } catch (NumberFormatException e3) {
                        throw e3;
                    }
                }
            }
        }
    } else {
        switch (instanceClassType) {
        // We know here the instanceClass.

        case "int":
        case "Integer":
            // Convert to integer.
            try {
                number = Integer.parseInt(str);
            } catch (NumberFormatException ex) {
                throw ex;
            }
            break;
        case "float":
        case "Float":
            try {
                number = Float.parseFloat(str);
            } catch (NumberFormatException ex) {
                throw ex;
            }
            break;
        case "BigDecimal":
        case "double":
        case "Double":
            try {
                number = Double.parseDouble(str);
            } catch (NumberFormatException ex) {
                throw ex;
            }

            break;
        case "Long":
        case "long":
            try {
                number = Long.parseLong(str);
            } catch (NumberFormatException ex) {
                throw ex;
            }
            break;
        default:
            throw new NumberFormatException("Unknown format.");
        }

    }

    return number;
}

From source file:org.accada.reader.hal.impl.sim.GraphicSimulator.java

/**
 * gets a property value as integer//  www.  j  ava2 s .c  o m
 * 
 * @param key of the property
 * @return property as integer value
 */
public int getProperty(String key) {
    String error;
    String value = props.getProperty(key);
    if (value == null) {
        error = "Value '" + key + "' not found in properties !";
    } else {
        try {
            return Integer.parseInt(value.trim());
        } catch (Exception e) {
            error = "Value '" + key + "' is not an integer !";
        }
    }
    throw new NumberFormatException(error);
}

From source file:edu.nyu.tandon.query.Query.java

/**
 * Interpret the given command, changing the static variables.
 * See the help printing code for possible commands.
 *
 * @param line the command line./*w  w  w . j  av  a  2 s .  c o m*/
 * @return false iff we should exit after this command.
 */
public boolean interpretCommand(final String line) {
    String[] part = line.substring(1).split("[ \t\n\r]+");

    final Command command;
    int i;

    if (part[0].length() == 0) {
        System.err.println("$                                                       prints this help.");
        System.err.println("$mode [time|short|long|snippet|trec <topicNo> <runTag>] chooses display mode.");
        System.err.println(
                "$select [<maxIntervals> <maxLength>] [all]              installs or removes an interval selector.");
        System.err.println(
                "$limit <max>                                            output at most <max> results per query.");
        System.err.println(
                "$divert [<filename>]                                    diverts output to <filename> or to stdout.");
        System.err.println(
                "$weight {index:weight}                                  set index weights (unspecified weights are set to 1).");
        System.err.println("$mplex [<on>|<off>]                                     set/unset multiplex mode.");
        System.err.println(
                "$equalize <sample>                                      equalize scores using the given sample size.");
        System.err.println(
                "$score {<scorerClass>(<arg>,...)[:<weight>]}            order documents according to <scorerClass>.");
        System.err.println(
                "$expand {<expanderClass>(<arg>,...)}                    expand terms and prefixes according to <expanderClass>.");
        System.err.println("$quit                                                   quits.");
        return true;
    }

    try {
        command = Command.valueOf(part[0].toUpperCase());
    } catch (IllegalArgumentException e) {
        System.err.println("Invalid command \"" + part[0] + "\"; type $ for help.");
        return true;
    }

    switch (command) {
    case MODE:
        if (part.length >= 2) {
            try {
                final OutputType tempMode = OutputType.valueOf(part[1].toUpperCase());

                if (tempMode != OutputType.TREC && part.length > 2)
                    System.err.println("Extra arguments.");
                else if (tempMode == OutputType.TREC && part.length != 4)
                    System.err.println("Missing or extra arguments.");
                else {
                    displayMode = tempMode;
                    if (displayMode == OutputType.TREC) {
                        trecTopicNumber = Integer.parseInt(part[2]);
                        trecRunTag = part[3];
                    }
                }
            } catch (IllegalArgumentException e) {
                System.err.println("Unknown mode: " + part[1]);
            }
        } else
            System.err.println("Missing mode.");
        break;

    case LIMIT:
        int out = -1;
        if (part.length == 2) {
            try {
                out = Integer.parseInt(part[1]);
            } catch (NumberFormatException e) {
            }
            if (out >= 0)
                maxOutput = out;
        }
        if (out < 0)
            System.err.println("Missing or incorrect limit.");
        break;

    case SELECT:
        int maxIntervals = -1, maxLength = -1;
        if (part.length == 1) {
            queryEngine.intervalSelector = null;
            System.err.println("Intervals have been disabled.");
        } else if (part.length == 2 && "all".equals(part[1])) {
            queryEngine.intervalSelector = new IntervalSelector(); // All intervals
            System.err.println("Interval selection has been disabled (will compute all intervals).");
        } else {
            if (part.length == 3) {
                try {
                    maxIntervals = Integer.parseInt(part[1]);
                    maxLength = Integer.parseInt(part[2]);
                    queryEngine.intervalSelector = new IntervalSelector(maxIntervals, maxLength);
                } catch (NumberFormatException e) {
                }
            }
            if (maxIntervals < 0 || maxLength < 0)
                System.err.println("Missing or incorrect selector parameters.");
        }
        break;

    case SCORE:
        final Scorer[] scorer = new Scorer[part.length - 1];
        final double[] weight = new double[part.length - 1];
        for (i = 1; i < part.length; i++)
            try {
                weight[i - 1] = loadClassFromSpec(part[i], scorer, i - 1);
                if (weight[i - 1] < 0)
                    throw new IllegalArgumentException("Weights should be non-negative");
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        if (i == part.length)
            queryEngine.score(scorer, weight);
        break;

    case EXPAND:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else if (part.length == 1) {
            queryEngine.transformer(null);
        } else {
            QueryTransformer[] t = new QueryTransformer[1];
            try {
                loadClassFromSpec(part[1], t, 0);
                queryEngine.transformer(t[0]);
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        }
        break;

    case MPLEX:
        if (part.length != 2 || (part.length == 2 && !"on".equals(part[1]) && !"off".equals(part[1])))
            System.err.println("Wrong argument(s) to command");
        else {
            if (part.length > 1)
                queryEngine.multiplex = "on".equals(part[1]);
            System.err.println("Multiplex: " + part[1]);
        }
        break;

    case DIVERT:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else {
            if (output != System.out)
                output.close();
            try {
                output = part.length == 1 ? System.out
                        : new PrintStream(new FastBufferedOutputStream(new FileOutputStream(part[1])));
            } catch (FileNotFoundException e) {
                System.err.println("Cannot create file " + part[1]);
                output = System.out;
            }
        }
        break;

    case WEIGHT:
        final Reference2DoubleOpenHashMap<Index> newIndex2Weight = new Reference2DoubleOpenHashMap<Index>();
        for (i = 1; i < part.length; i++) {
            final int pos = part[i].indexOf(':');
            if (pos < 0) {
                System.err.println("Missing colon: " + part[i]);
                break;
            } else if (!queryEngine.indexMap.containsKey(part[i].substring(0, pos))) {
                System.err.println("Unknown index: " + part[i].substring(0, pos));
                break;
            }
            try {
                double newWeight = Double.parseDouble(part[i].substring(pos + 1));
                newIndex2Weight.put(queryEngine.indexMap.get(part[i].substring(0, pos)), newWeight);
            } catch (NumberFormatException e) {
                System.err.println("Wrong weight specification: " + part[i].substring(pos + 1));
                break;
            }
        }
        if (i == part.length) {
            if (i > 1)
                queryEngine.setWeights(newIndex2Weight);
            for (String key : queryEngine.indexMap.keySet())
                System.err.print(key + ":" + newIndex2Weight.getDouble(queryEngine.indexMap.get(key)) + " ");
            System.err.println();
        }
        break;

    case EQUALIZE:
        try {
            if (part.length != 2)
                throw new NumberFormatException("Illegal number of arguments");
            queryEngine.equalize(Integer.parseInt(part[1]));
            System.err.println("Equalization sample set to " + Integer.parseInt(part[1]));
        } catch (NumberFormatException e) {
            System.err.println(e.getMessage());
        }
        break;

    case QUIT:
        return false;
    }

    return true;
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The received content is treated as
 * {@link Double} value. If the value is a plain {@link Double} value it is returned right away. Double values contained inside {@link String}
 * instances are parsed out by {@link Double#parseDouble(String)}. If parsing fails or the type is not of the referenced ones the method 
 * throws a {@link NumberFormatException}
 * @param jsonObject//www .j av  a 2s. c o  m
 *          The {@link JSONObject} to read the value from (null is not permitted as input)
 * @param fieldPath
 *          Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input)
 * @param required
 *          Field is required to exist at the end of the given path 
 * @return
 *          Value found at the end of the provided path. An empty path simply returns the input
 * @throws JSONException
 *          Thrown in case extracting values from the {@link JSONObject} fails for any reason
 * @throws IllegalArgumentException
 *          Thrown in case a provided parameter does not comply with the restrictions
 * @throws NoSuchElementException
 *          Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject}
 * @throws NumberFormatException
 *          Thrown in case parsing out an {@link Integer} from the retrieved field value fails for any format related reason 
 */
public Double getDoubleFieldValue(final JSONObject jsonObject, final String[] fieldPath, final boolean required)
        throws JSONException, IllegalArgumentException, NoSuchElementException, NumberFormatException {

    Object value = getFieldValue(jsonObject, fieldPath, required);
    if (value == null && !required)
        return null;

    if (value instanceof Double)
        return (Double) value;
    else if (value instanceof String)
        return Double.parseDouble((String) value);

    throw new NumberFormatException("Types of " + (value != null ? value.getClass().getName() : "null")
            + " cannot be parsed into a valid double representation");
}

From source file:org.displaytag.util.NumberUtils.java

/**
 * <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>
 * /*from   w w  w . j  a v a  2 s.c o m*/
 * <p>Returns <code>null</code> if the string is <code>null</code>.</p>
 *
 * @param str  a <code>String</code> to convert, may be null
 * @return converted <code>BigDecimal</code>
 * @throws NumberFormatException if the value cannot be converted
 */
public static BigDecimal createBigDecimal(String str) {
    if (str == null) {
        return null;
    }
    // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
    if (StringUtils.isBlank(str)) {
        throw new NumberFormatException("A blank string is not a valid number");
    }
    return new BigDecimal(str);
}

From source file:net.wastl.webmail.misc.Helper.java

public static String decryptTEA(String src) {
    StringTokenizer tok = new StringTokenizer(src, ": ");
    byte[] key = new BigInteger(str_key, 16).toByteArray();
    TEA tea = new TEA(key);
    byte inb[] = new byte[tok.countTokens()];
    for (int i = 0; i < inb.length && tok.hasMoreTokens(); i++) {
        String s = tok.nextToken();
        try {/*w  ww  . ja  va 2  s .  com*/
            inb[i] = (byte) (Integer.parseInt(s, 16) - 128);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Could not convert string '" + s + "' to byte.");
        }
    }
    byte dec[] = tea.decode(inb, inb.length);
    String s = new String(dec);
    // log.debug("encryptTEA: Returning "+s);
    java.util.regex.Matcher m = nonGraphPattern.matcher(s);
    if (!m.find())
        return s;
    log.warn("Executed work-around for TEA decryption bug");
    String fixedS = m.replaceFirst("");
    if (s.equals(fixedS))
        log.warn("The TEA work-around was not needed in this case");
    // I believe the rot of the bug is with padding in the TEA.decode()
    // method(s).  I do not have time to fix the real problem there.
    return fixedS;
}

From source file:de.codesourcery.jasm16.utils.Misc.java

public static long parseHexString(String s) throws NumberFormatException {

    String trimmed = s.toLowerCase().trim();
    if (trimmed.startsWith("0x")) {
        trimmed = trimmed.substring(2, trimmed.length());
    }//from www.j  a  v a  2s .c om

    long result = 0;
    for (int i = 0; i < trimmed.length(); i++) {
        result = result << 4;
        int nibble = -1;
        for (int j = 0; j < HEX_CHARS.length; j++) {
            if (HEX_CHARS[j] == trimmed.charAt(i)) {
                nibble = j;
                break;
            }
        }
        if (nibble < 0) {
            throw new NumberFormatException("Not a valid hex string: '" + s + "'");
        }
        result = result | nibble;
    }
    return result;
}

From source file:edu.nyu.tandon.tool.RawDocHits_deprecated.java

/**
 * Interpret the given command, changing the static variables.
 * See the help printing code for possible commands.
 *
 * @param line the command line./*  ww  w  .j ava  2  s  . com*/
 * @return false iff we should exit after this command.
 */
public boolean interpretCommand(final String line) {
    String[] part = line.substring(1).split("[ \t\n\r]+");

    final Command command;
    int i;

    if (part[0].length() == 0) {
        System.err.println("$                                                       prints this help.");
        System.err.println("$mode [time|short|long|snippet|trec <topicNo> <runTag>] chooses display mode.");
        System.err.println(
                "$select [<maxIntervals> <maxLength>] [all]              installs or removes an interval selector.");
        System.err.println(
                "$limit <max>                                            output at most <max> results per query.");
        System.err.println(
                "$divert [<filename>]                                    diverts output to <filename> or to stdout.");
        System.err.println(
                "$weight {index:weight}                                  set index weights (unspecified weights are set to 1).");
        System.err.println("$mplex [<on>|<off>]                                     set/unset multiplex mode.");
        System.err.println(
                "$equalize <sample>                                      equalize scores using the given sample size.");
        System.err.println(
                "$score {<scorerClass>(<arg>,...)[:<weight>]}            order documents according to <scorerClass>.");
        System.err.println(
                "$expand {<expanderClass>(<arg>,...)}                    expand terms and prefixes according to <expanderClass>.");
        System.err.println("$quit                                                   quits.");
        return true;
    }

    try {
        command = Command.valueOf(part[0].toUpperCase());
    } catch (IllegalArgumentException e) {
        System.err.println("Invalid command \"" + part[0] + "\"; type $ for help.");
        return true;
    }

    switch (command) {
    case MODE:
        if (part.length >= 2) {
            try {
                final OutputType tempMode = OutputType.valueOf(part[1].toUpperCase());

                if (tempMode != OutputType.TREC && part.length > 2)
                    System.err.println("Extra arguments.");
                else if (tempMode == OutputType.TREC && part.length != 4)
                    System.err.println("Missing or extra arguments.");
                else {
                    displayMode = tempMode;
                    if (displayMode == OutputType.TREC) {
                        trecTopicNumber = Integer.parseInt(part[2]);
                        trecRunTag = part[3];
                    }
                }
            } catch (IllegalArgumentException e) {
                System.err.println("Unknown mode: " + part[1]);
            }
        } else
            System.err.println("Missing mode.");
        break;

    case LIMIT:
        int out = -1;
        if (part.length == 2) {
            try {
                out = Integer.parseInt(part[1]);
            } catch (NumberFormatException e) {
            }
            if (out >= 0)
                maxOutput = out;
        }
        if (out < 0)
            System.err.println("Missing or incorrect limit.");
        break;

    case SELECT:
        int maxIntervals = -1, maxLength = -1;
        if (part.length == 1) {
            queryEngine.intervalSelector = null;
            System.err.println("Intervals have been disabled.");
        } else if (part.length == 2 && "all".equals(part[1])) {
            queryEngine.intervalSelector = new IntervalSelector(); // All intervals
            System.err.println("Interval selection has been disabled (will compute all intervals).");
        } else {
            if (part.length == 3) {
                try {
                    maxIntervals = Integer.parseInt(part[1]);
                    maxLength = Integer.parseInt(part[2]);
                    queryEngine.intervalSelector = new IntervalSelector(maxIntervals, maxLength);
                } catch (NumberFormatException e) {
                }
            }
            if (maxIntervals < 0 || maxLength < 0)
                System.err.println("Missing or incorrect selector parameters.");
        }
        break;

    case SCORE:
        final Scorer[] scorer = new Scorer[part.length - 1];
        final double[] weight = new double[part.length - 1];
        for (i = 1; i < part.length; i++)
            try {
                weight[i - 1] = loadClassFromSpec(part[i], scorer, i - 1);
                if (weight[i - 1] < 0)
                    throw new IllegalArgumentException("Weights should be non-negative");
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        if (i == part.length)
            queryEngine.score(scorer, weight);
        break;

    case EXPAND:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else if (part.length == 1) {
            queryEngine.transformer(null);
        } else {
            QueryTransformer[] t = new QueryTransformer[1];
            try {
                loadClassFromSpec(part[1], t, 0);
                queryEngine.transformer(t[0]);
            } catch (Exception e) {
                System.err.print("Error while parsing specification: ");
                e.printStackTrace(System.err);
                break;
            }
        }
        break;

    case MPLEX:
        if (part.length != 2 || (part.length == 2 && !"on".equals(part[1]) && !"off".equals(part[1])))
            System.err.println("Wrong argument(s) to command");
        else {
            if (part.length > 1)
                queryEngine.multiplex = "on".equals(part[1]);
            System.err.println("Multiplex: " + part[1]);
        }
        break;

    case DIVERT:
        if (part.length > 2)
            System.err.println("Wrong argument(s) to command");
        else {
            if (output != System.out)
                output.close();
            try {
                output = part.length == 1 ? System.out
                        : new PrintStream(new FastBufferedOutputStream(
                                new FileOutputStream(part[1] + "-" + batch++ + ".txt")));
                outputName = part[1];
            } catch (FileNotFoundException e) {
                System.err.println("Cannot create file " + part[1]);
                output = System.out;
            }
        }
        break;

    case EQUALIZE:
        try {
            if (part.length != 2)
                throw new NumberFormatException("Illegal number of arguments");
            queryEngine.equalize(Integer.parseInt(part[1]));
            System.err.println("Equalization sample set to " + Integer.parseInt(part[1]));
        } catch (NumberFormatException e) {
            System.err.println(e.getMessage());
        }
        break;

    case QUIT:
        return false;
    }
    return true;
}

From source file:org.accada.hal.impl.sim.GraphicSimulator.java

/**
 * gets a property value as integer/* w  w  w.  j ava2  s . co m*/
 * 
 * @param key of the property
 * @return property as integer value
 */
public int getProperty(String key) {
    String error;
    if (!propsConfig.containsKey(key)) {
        error = "Value '" + key + "' not found in properties !";
    } else {
        try {
            return propsConfig.getInt(key);
        } catch (Exception e) {
            error = "Value '" + key + "' is not an integer !";
        }
    }
    throw new NumberFormatException(error);
}

From source file:org.apache.hadoop.hive.druid.DruidStorageHandlerUtils.java

@Nullable
static Integer getIntegerProperty(Table table, String propertyName) {
    String val = getTableProperty(table, propertyName);
    if (val == null) {
        return null;
    }/*w  ww .j a  va 2  s. c om*/
    try {
        return Integer.parseInt(val);
    } catch (NumberFormatException e) {
        throw new NumberFormatException(String
                .format("Exception while parsing property[%s] with Value [%s] as Integer", propertyName, val));
    }
}