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:mondrian.spi.impl.JdbcDialectImpl.java

public void quoteDateLiteral(StringBuilder buf, String value) {
    // NOTE jvs 1-Jan-2007: Check that the supplied literal is in valid
    // SQL:2003 date format.  A hack in
    // RolapSchemaReader.lookupMemberChildByName looks for
    // NumberFormatException to suppress it, so that is why
    // we convert the exception here.
    final Date date;
    try {/*  w  ww  .  j a v  a  2s  . c  o  m*/
        date = Date.valueOf(value);
    } catch (IllegalArgumentException ex) {
        throw new NumberFormatException("Illegal DATE literal:  " + value);
    }
    quoteDateLiteral(buf, value, date);
}

From source file:org.lockss.util.PlatformUtil.java

public static double parseDouble(String str) {
    if (isBuggyDoubleString(str)) {
        throw new NumberFormatException("Buggy double string");
    }//from w  ww . j av  a 2s .  c o m
    return Double.parseDouble(str);
}

From source file:mondrian.spi.impl.JdbcDialectImpl.java

public void quoteTimeLiteral(StringBuilder buf, String value) {
    // NOTE jvs 1-Jan-2007:  See quoteDateLiteral for explanation.
    try {//from w  w w  .  j a v  a2 s. c  o  m
        Time.valueOf(value);
    } catch (IllegalArgumentException ex) {
        throw new NumberFormatException("Illegal TIME literal:  " + value);
    }
    buf.append("TIME ");
    Util.singleQuoteString(value, buf);
}

From source file:uk.ac.gda.ui.components.NumberEditorControl.java

public void setDigits(int value) throws NumberFormatException {
    if (!controlModel.getBindingPropertyType().equals(double.class)) {
        throw new NumberFormatException("Invalid data type set to digits");
    }//from   ww w  .  j  a  va 2  s  . co m
    controlModel.setDigits(value);
    numberLabelValueBinding.updateModelToTarget();
    if (useSpinner) {
        incrementLabelBinding.updateModelToTarget();
    }
}

From source file:org.hibernate.validator.internal.util.logging.Log.java

public NumberFormatException getCharacterIsNotADigitException(final char character) {
    return new NumberFormatException(MESSAGE.getCharacterIsNotADigitException(character));
}

From source file:erigo.filewatch.FileWatch.java

/**
 * Creates a WatchService and registers the given directory
 *///from  w  ww.j  a v a  2s  . c  om
// FileWatch(Path watchDir, String outputFilename, Path outputDirI) throws IOException {
FileWatch(String[] argsI) throws IOException {

    //
    // Parse command line arguments
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Boolean options (only the flag, no argument)
    options.addOption("h", "help", false, "Print this message.");
    options.addOption("a", "adjust_latency", false,
            "Divide latency results by 2 because test data files are from a recaster (round-trip).");
    options.addOption("d", "disp_recaster", false, "Display results when operating in recaster mode.");
    // Command line options that include an argument
    Option nextOption = Option.builder("i").argName("watchdir").hasArg().desc(
            "Directory to watch for incoming test data files (must be an existing directory); default = \""
                    + DEFAULT_WATCH_DIR + "\".")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("o").argName("outfilename").hasArg()
            .desc("Name of the output metrics data file; must be a new file.").build();
    options.addOption(nextOption);
    nextOption = Option.builder("p").argName("pollinterval_msec").hasArg().desc(
            "Watch for new files by polling (don't use Java WatchService); sleep for <pollinterval_msec> (milliseconds) between scans.")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("r").argName("recasterdir").hasArg()
            .desc("Recast test data files to the specified output directory (must be an existing directory).")
            .build();
    options.addOption(nextOption);
    nextOption = Option.builder("t").argName("plottitle").hasArg()
            .desc("Custom title for throughput and latency plots.").build();
    options.addOption(nextOption);

    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argsI);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("h")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(100);
        formatter.printHelp("FileWatch", options);
        return;
    }
    bAdjustLatencyMetrics = line.hasOption("a");
    bOutputResultsInRecastMode = line.hasOption("d");
    // Watch directory
    String watchDirName = line.getOptionValue("i", DEFAULT_WATCH_DIR);
    Path watchDir = Paths.get(watchDirName);
    if (!watchDir.toFile().isDirectory()) {
        System.err.println("\nThe given watch directory does not exist.");
        System.exit(-1);
    }
    // Recaster directory
    Path outputDirPath = null;
    String outputDirName = line.getOptionValue("r");
    if (outputDirName != null) {
        outputDirPath = Paths.get(outputDirName);
        if (!outputDirPath.toFile().isDirectory()) {
            System.err.println("\nThe given recaster output directory does not exist.");
            System.exit(-1);
        }
        // Make sure watchDir and outputDir aren't the same
        if (watchDir.toAbsolutePath().compareTo(outputDirPath.toAbsolutePath()) == 0) {
            System.err.println("\nThe recaster output directory cannot be the same as the watch directory.");
            System.exit(-1);
        }
        bRecast = true;
        outputDir = outputDirPath.toFile();
    }
    // Output filename
    String outputFilename = line.getOptionValue("o");
    if ((outputFilename == null) && (!bRecast || bOutputResultsInRecastMode)) {
        System.err.println("\nMust specify the name of the output data file.");
        System.exit(-1);
    }
    if (outputFilename != null) {
        File outputFile = new File(outputFilename);
        if (outputFile.isDirectory()) {
            System.err.println(
                    "\nThe given output data file is the name of a directory; must specify an output filename.");
            System.exit(-1);
        } else if (outputFile.isFile()) {
            System.err.println(
                    "\nThe given output data file is the name of an existing file; must specify a new filename.");
            System.exit(-1);
        }
    }
    // Use polling to check for new files?
    String pollIntervalStr = line.getOptionValue("p");
    if (pollIntervalStr != null) {
        try {
            pollInterval = Integer.parseInt(pollIntervalStr);
            if ((pollInterval <= 0) || (pollInterval > 1000)) {
                throw new NumberFormatException("Illegal value");
            }
        } catch (NumberFormatException nfe) {
            System.err.println("\nPoll interval must be an integer in the range 0 < x <= 1000");
            System.exit(-1);
        }
    }
    // Title for the throughput and latency plots
    customPlotTitle = line.getOptionValue("t", "");

    // Make sure "end.txt" doesn't already exist in the directory; this file is our signal
    // that we're done processing
    File endFile = new File(watchDir.toFile(), "end.txt");
    if (endFile.exists()) {
        System.err.println("\nMust delete \"" + endFile + "\" before running test.");
        System.exit(-1);
    }
    // If we are recasting, make sure "end.txt" doesn't exist in the output directory either
    if (outputDirPath != null) {
        endFile = new File(outputDirPath.toFile(), "end.txt");
        if (endFile.exists()) {
            System.err.println("\nMust delete \"" + endFile + "\" in output directory before running test.");
            System.exit(-1);
        }
    }

    if (pollInterval > 0) {
        System.err
                .println("\nWatching directory \"" + watchDir + "\" for incoming files; using polling method");
        processEvents_polling(watchDir.toFile());
    } else {
        // Register the directory with the WatchService
        // Only collect data for ENTRY_CREATE events.  Even if a file is just
        // copied into a directory, several ENTRY_MODIFY events can be
        // triggered because the file's content and its parameters (such as
        // timestamp) are independently set.
        watchDir.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE },
                SensitivityWatchEventModifier.HIGH);
        System.err.println(
                "\nWatching directory \"" + watchDir + "\" for incoming files; using WatchService events");
        processEvents_watchservice();
        watcher.close();
    }

    if (!bRecast || bOutputResultsInRecastMode) {
        System.err.println("\nWrite data to file \"" + outputFilename + "\"...");
    }
    processData(outputFilename);

    System.err.println(
            "\nFileWatch received a total of " + num_received_files + " files (not including \"end.txt\")");
    System.err
            .println("In processing, " + num_skipped_files + " files were skipped (due to wrong name format)");
    int num_files_processed = num_received_files - num_skipped_files;
    System.err.println(
            "Thus, a total of " + num_files_processed + " files with properly formatted names were processed");

    System.err.println("\nTest is complete.");

}

From source file:mondrian.spi.impl.JdbcDialectImpl.java

public void quoteTimestampLiteral(StringBuilder buf, String value) {
    // NOTE jvs 1-Jan-2007:  See quoteTimestampLiteral for explanation.
    try {/* w  w  w .  j ava  2 s.c o m*/
        Timestamp.valueOf(value);
    } catch (IllegalArgumentException ex) {
        throw new NumberFormatException("Illegal TIMESTAMP literal:  " + value);
    }
    buf.append("TIMESTAMP ");
    Util.singleQuoteString(value, buf);
}

From source file:com.ebay.erl.mobius.core.model.Tuple.java

/**
 * Get the value of the given column <code>name</code> in
 * the <code>expecting_type</code>.
 * <p>//  w  w  w  . j  a  v  a2  s.c  o  m
 * 
 * If the original <code>value</code> is not in the exact
 * same <code>expecting_type</code>, Mobius will try to
 * convert it to the <code>expecting_type</code> and return
 * it.
 * <p>
 * 
 * If the original <code>value</code> is null, then 
 * <code>default_value</code> is returned.
 * 
 * @param expecting_type user specified type for the returned value. 
 * @param name the name of a column within this tuple.
 * @param value the original value of the column <code>name</code>
 * @param default_value if the original value is null, then <code>default_value</code>
 * is returned.
 * @return
 */
protected Object get(byte expecting_type, String name, Object value, Object default_value) {
    byte actual_type = Tuple.getType(value);

    if (expecting_type == Tuple.getType(value)) {
        return value;
    } else {
        // expecting type and actual type are different.         
        if (Tuple.isNumericalType(expecting_type) && Tuple.isNumericalType(actual_type)) {
            if (value == null) {
                return default_value;
            }

            // expecting value and actual value are both numerical type,
            // but not exact the same, perform transformation.
            switch (expecting_type) {
            case BYTE_TYPE:
                return ((Number) value).byteValue();
            case SHORT_TYPE:
                return ((Number) value).shortValue();
            case INTEGER_TYPE:
                return ((Number) value).intValue();
            case LONG_TYPE:
                return ((Number) value).longValue();
            case FLOAT_TYPE:
                return ((Number) value).floatValue();
            case DOUBLE_TYPE:
                return ((Number) value).doubleValue();
            default:
                throw new IllegalArgumentException(
                        String.format("%02X", expecting_type) + " is not numerical type.");
            }
        } else if (expecting_type == STRING_TYPE && actual_type != STRING_TYPE) {
            if (value == null) {
                return default_value;
            }

            LOGGER.trace("Accessing column[" + name + "], the expecting type is ["
                    + Tuple.getTypeString(expecting_type) + "], " + "but actual type is ["
                    + Tuple.getTypeString(actual_type) + "], using toString() to get the value.");
            // expecting type is string, but the actual type is not string, 
            // convert it to string by calling toString().
            return value.toString();
        } else if (Tuple.isDateType(expecting_type) && Tuple.isDateType(actual_type)) {
            // date type, but the expecting type is not the same as the actual type.
            // Ex:, expecting java.sql.Date, but actual is java.sql.Timestamp
            if (value == null) {
                return default_value;
            }

            // use java.util.Date as the actual type would be
            // either java.sql.Date, java.sql.Time or 
            // java.sql.Timestamp.
            java.util.Date actual_value = (java.util.Date) value;

            switch (expecting_type) {
            case Tuple.DATE_TYPE:
                java.sql.Date sqlDate = new java.sql.Date(actual_value.getTime());
                return sqlDate;
            case Tuple.TIME_TYPE:
                java.sql.Time sqlTime = new java.sql.Time(actual_value.getTime());
                return sqlTime;
            case Tuple.TIMESTAMP_TYPE:
                java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(actual_value.getTime());
                return sqlTimeStamp;
            default:
                throw new IllegalArgumentException(Tuple.getTypeString(actual_type) + " is not a date type.");
            }

        } else if (Tuple.isDateType(expecting_type) && actual_type == STRING_TYPE) {
            // expecting type is date type, but the actual type is string
            switch (expecting_type) {
            case Tuple.DATE_TYPE:
                java.sql.Date sqlDate = java.sql.Date.valueOf((String) value);
                return sqlDate;
            case Tuple.TIME_TYPE:
                java.sql.Time sqlTime = java.sql.Time.valueOf((String) value);
                return sqlTime;
            case Tuple.TIMESTAMP_TYPE:
                java.sql.Timestamp sqlTimeStamp = java.sql.Timestamp.valueOf((String) value);
                return sqlTimeStamp;
            default:
                throw new IllegalArgumentException(Tuple.getTypeString(actual_type) + " is not a date type.");
            }
        } else if (Tuple.isNumericalType(expecting_type) && actual_type == STRING_TYPE) {
            if (value == null) {
                return default_value;
            }

            // expecting type is numerical, but the actual type is string, 
            // try to convert it into numerical value
            String value_str = (String) value;
            try {
                switch (expecting_type) {
                case BYTE_TYPE:
                    return Byte.parseByte(value_str);
                case SHORT_TYPE:
                    return Short.parseShort(value_str);
                case INTEGER_TYPE:
                    return Integer.parseInt(value_str);
                case LONG_TYPE:
                    return Long.parseLong(value_str);
                case FLOAT_TYPE:
                    return Float.parseFloat(value_str);
                case DOUBLE_TYPE:
                    return Double.parseDouble(value_str);
                default:
                    throw new IllegalArgumentException(
                            String.format("%02X", expecting_type) + " is not numerical type.");
                }
            } catch (NumberFormatException e) {
                throw new NumberFormatException("The value of column[" + name + "] is [" + value_str
                        + "] and cannot be converted into " + Tuple.getTypeString(expecting_type));
            }
        } else if (expecting_type == BOOLEAN_TYPE && actual_type == STRING_TYPE) {
            return Boolean.valueOf((String) value);
        }
        throw new ClassCastException("Column [" + name + "] is " + Tuple.getTypeString(actual_type)
                + ", cannot be converted into " + Tuple.getTypeString(expecting_type));
    }
}

From source file:com.glaf.core.util.GetterUtils.java

public static int getIntegerStrict(String value) {
    int length = value.length();

    if (length <= 0) {
        throw new NumberFormatException("Unable to parse " + value);
    }//from  ww w . j a va  2s  .  co m

    int index = 0;
    int limit = -Integer.MAX_VALUE;
    boolean negative = false;

    char c = value.charAt(0);

    if (c < CharPool.NUMBER_0) {
        if (c == CharPool.MINUS) {
            limit = Integer.MIN_VALUE;
            negative = true;
        } else if (c != CharPool.PLUS) {
            throw new NumberFormatException("Unable to parse " + value);
        }

        if (length == 1) {
            throw new NumberFormatException("Unable to parse " + value);
        }

        index++;
    }

    int smallLimit = limit / 10;

    int result = 0;

    while (index < length) {
        if (result < smallLimit) {
            throw new NumberFormatException("Unable to parse " + value);
        }

        c = value.charAt(index++);

        if ((c < CharPool.NUMBER_0) || (c > CharPool.NUMBER_9)) {
            throw new NumberFormatException("Unable to parse " + value);
        }

        int number = c - CharPool.NUMBER_0;

        result *= 10;

        if (result < (limit + number)) {
            throw new NumberFormatException("Unable to parse " + value);
        }

        result -= number;
    }

    if (negative) {
        return result;
    } else {
        return -result;
    }
}

From source file:org.uva.itast.blended.omr.OMRUtils.java

/**
 * Mtodo para guardar los resultados del proceso de reconocimiento de
 * marcas//from   www.j av  a2s. c  om
 * 
 * @param outputdir
 * @param inputpath
 * @param template
 * @throws FileNotFoundException
 */
public static File saveOMRResults(String inputpath, String outputdir, OMRTemplate template,
        String templateIdName, String userIdName) throws FileNotFoundException, NumberFormatException {
    Hashtable<String, Field> fields = template.getSelectedPage().getFields();
    Field templateIdField = fields.get(templateIdName);
    Field useridField = fields.get(userIdName);
    try {
        if (useridField == null || templateIdField == null) // simulate a
            // NumberFormat.
            throw new NumberFormatException(
                    "There is no " + TEMPLATEID_FIELDNAME + " field defined in the template!!");

        /**
         * Force to cast to integer to avoid the injection of paths in the
         * Ids.
         */
        int useridInt = useridField.getValue() == null ? -1 : Integer.parseInt(useridField.getValue());
        int templateIdInt = templateIdField.getValue() == null ? -1
                : Integer.parseInt(templateIdField.getValue());

        File dir = new File(outputdir); // que venga de parametro
        dir.mkdirs(); // ensure dir exists
        // File outputFile = new File(dir, "omr_result["+
        // template.getTemplateID() + "].txt");
        File outputFile = new File(dir, "omr_result[" + (int) (templateIdInt / 10) + "].txt");

        PrintWriter out = new PrintWriter(new FileOutputStream(outputFile, true));
        // TODO: solo volcar la pgina seleccionada en esta fase. Luego se
        // volcarn las dos pginas en el otro proceso
        // de volcado de resultados finales...

        PageTemplate page = template.getSelectedPage();
        fields = page.getFields();
        out.println("Filename=" + inputpath);

        out.println("[Page" + page.getPageNumber() + "]");
        for (int k = 0; k < page.getMarks().size(); k++) {
            Field field = fields.get(page.getMarks().elementAt(k));
            out.println(field.getName() + "=" + field.getValue());
        }

        out.close();
        return outputFile;
    } catch (NumberFormatException e) {
        logger.error("saveOMRResults: Report can't be written. Both ids are not available: " + templateIdName //$NON-NLS-1$
                + "=" + templateIdField + " and " + userIdName + "=" + useridField + ".", e);
    }
    return null;
}