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() 

Source Link

Document

Constructs a NumberFormatException with no detail message.

Usage

From source file:org.raegdan.troca.Main.java

public static void main(String[] args) {

    String fromCurrency = null, toCurrency = null;
    ExchangeAPI handler = null;//from   w ww .  ja v  a 2 s. c  o m
    TrendStorage storage = null;

    if (args.length == 0)
        usage();

    for (int i = 0; i < args.length; i++) {
        switch (args[i]) {
        case "--from":
        case "-f":
            i++;
            if (i >= args.length)
                usage("--from requires an argument");
            fromCurrency = args[i];
            break;

        case "--to":
        case "-t":
            i++;
            if (i >= args.length)
                usage("--to requires an argument");
            toCurrency = args[i];
            break;

        case "--help":
        case "-h":
            usage();
            break;

        case "--source":
        case "-s":
            i++;
            if (i >= args.length)
                usage("--source requires an argument");
            switch (args[i]) {
            case "coinbase":
            case "c":
                handler = new CoinbaseComExchangeAPI();
                break;

            case "yahoo":
            case "y":
                handler = new YahooFinanceExchangeAPI();
                break;

            default:
                usage(args[i] + " is not a valid argument for --source, check available sources");
            }
            break;

        case "--db-type":
            i++;
            if (i >= args.length)
                usage("--db-type requires an argument");
            dbType = args[i];
            dbTypeIsSet = true;
            break;

        case "--db":
            i++;
            if (i >= args.length)
                usage("--db requires an argument");
            db = args[i];
            dbIsSet = true;
            break;

        case "--db-type-json-force":
            dbTypeJSONForce = true;
            dbTypeJSONForceIsSet = true;
            break;

        case "--verbose":
        case "-v":
            verbose = true;
            break;

        case "--json":
        case "-j":
            json = true;
            break;

        case "--fancy":
            fancyJson = true;
            break;

        case "--daemon":
            i++;
            if (i >= args.length)
                usage("--daemon requires an argument");

            try {
                daemon = Integer.parseInt(args[i]);
            } catch (NumberFormatException e) {
                usage(args[i] + " is not a valid argument for --daemon, integer number needed");
            }

            if (daemon < 5000) {
                usage(args[i] + " is not a valid argument for --daemon, range is 5000 ... +INF");
            }

            break;

        case "-l":
        case "--langolier":
            i++;
            if (i >= args.length)
                usage("--langolier requires an argument");

            try {
                langolier = Integer.parseInt(args[i]);
                if (langolier < 1)
                    throw new NumberFormatException();
            } catch (NumberFormatException e) {
                usage(args[i] + " is not a valid argument for --langolier, integer number above zero needed");
            }

            break;

        case "--quiet":
        case "-q":
            quiet = true;
            break;

        case "--timestamp":
            prependTimestamp = true;
            break;

        default:
            usage("unknown argument: " + args[i]);
        }

    }

    if (dbIsSet != dbTypeIsSet) {
        usage("--db and --db-type may be used only together.");
    }

    if (quiet && (prependTimestamp || verbose || json)) {
        usage("--timestamp, --json and --verbose make no sense together with --quiet.");
    }

    if (quiet && !dbIsSet) {
        usage("--quiet makes no sense without database output (--db-type and --db).");
    }

    if (langolier > 0 && !dbIsSet) {
        usage("--langolier is set without --db and --db-type: nowhere to expunge old entries from!");
    }

    if (dbIsSet) {
        switch (dbType) {
        case "json":
        case "j":
            try {
                storage = new JSONTrendStorage(db, dbTypeJSONForce);
            } catch (Exception e) {
                printException(e);
            }
            break;

        default:
            if (dbTypeJSONForceIsSet) {
                usage("--db-type-json-force is applicable to --db-type json only.");
            }

            usage("unknown database type: " + dbType);
        }
    }

    if (handler == null)
        handler = new YahooFinanceExchangeAPI();

    if (fancyJson && !json) {
        usage("--fancy is not allowed without --json");
    }

    if (fromCurrency == null || toCurrency == null) {
        usage("missing some mandatory argument(s)");
    }

    if (verbose)
        greet(handler.getDataSource(), (dbIsSet) ? storage.getTrendStorage() : null);

    do {
        HashMap<String, Double> rates = queryRate(parseCurrencies(fromCurrency), parseCurrencies(toCurrency),
                handler);

        if (json)
            printRatesAsJSON(rates, fancyJson);
        else
            printRates(rates);

        if (daemon > 0)
            out();

        if (dbIsSet) {
            try {
                storage.storeRates(rates, handler.getDataSource(), (int) (new Date().getTime() / 1000),
                        (langolier > 0), langolier);
            } catch (Exception e) {
                printException(e);
            }
        }

    } while (sleeper(daemon));

    System.exit(0);
}

From source file:fredboat.command.music.control.SelectCommand.java

static void select(CommandContext context) {
    Member invoker = context.invoker;
    GuildPlayer player = PlayerRegistry.getOrCreate(context.guild);
    VideoSelection selection = VideoSelection.get(invoker);
    if (selection == null) {
        context.reply(context.i18n("selectSelectionNotGiven"));
        return;/*from   w w  w .j  a  va2 s .  co m*/
    }

    try {
        //Step 1: Parse the issued command for numbers

        // LinkedHashSet to handle order of choices + duplicates
        LinkedHashSet<Integer> requestChoices = new LinkedHashSet<>();

        // Combine all args and the command trigger. if the trigger is not a number it will be sanitized away
        String commandOptions = (context.trigger + " " + context.rawArgs).trim();
        String sanitizedQuery = sanitizeQueryForMultiSelect(commandOptions).trim();

        if (StringUtils.isNumeric(commandOptions)) {
            requestChoices.add(Integer.valueOf(commandOptions));
        } else if (TextUtils.isSplitSelect(sanitizedQuery)) {
            // Remove all non comma or number characters
            String[] querySplit = sanitizedQuery.split(",|\\s");

            for (String value : querySplit) {
                if (StringUtils.isNumeric(value)) {
                    requestChoices.add(Integer.valueOf(value));
                }
            }
        }

        //Step 2: Use only valid numbers (usually 1-5)

        ArrayList<Integer> validChoices = new ArrayList<>();
        // Only include valid values which are 1 to <size> of the offered selection
        for (Integer value : requestChoices) {
            if (1 <= value && value <= selection.choices.size()) {
                validChoices.add(value);
            }
        }

        //Step 3: Make a selection based on the order of the valid numbers

        // any valid choices at all?
        if (validChoices.isEmpty()) {
            throw new NumberFormatException();
        } else {
            AudioTrack[] selectedTracks = new AudioTrack[validChoices.size()];
            StringBuilder outputMsgBuilder = new StringBuilder();

            for (int i = 0; i < validChoices.size(); i++) {
                selectedTracks[i] = selection.choices.get(validChoices.get(i) - 1);

                String msg = context.i18nFormat("selectSuccess", validChoices.get(i),
                        selectedTracks[i].getInfo().title,
                        TextUtils.formatTime(selectedTracks[0].getInfo().length));
                if (i < validChoices.size()) {
                    outputMsgBuilder.append("\n");
                }
                outputMsgBuilder.append(msg);

                player.queue(new AudioTrackContext(selectedTracks[i], invoker));
            }

            VideoSelection.remove(invoker);
            TextChannel tc = FredBoat.getTextChannelById(selection.channelId);
            if (tc != null) {
                CentralMessaging.editMessage(tc, selection.outMsgId,
                        CentralMessaging.from(outputMsgBuilder.toString()));
            }

            player.setPause(false);
            context.deleteMessage();
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        context.reply(context.i18nFormat("selectInterval", selection.choices.size()));
    }
}

From source file:gedi.util.MathUtils.java

/**
 * Throws an exception if n is either a real or to big to be represented by a byte.
 * @param n/*from w ww .j a  v  a2  s . c o m*/
 * @return
 */
public static byte byteValueExact(Number n) {
    if (n instanceof Byte)
        return n.byteValue();
    double d = n.doubleValue();
    long l = n.longValue();
    if (d == (double) l) {
        if (l >= Byte.MIN_VALUE && l <= Byte.MAX_VALUE)
            return (byte) l;
    }
    throw new NumberFormatException();
}

From source file:de.akquinet.gomobile.androlog.test.PostReporterTest.java

public void testPost() {
    Log.init(getContext());// w ww.  ja  va2  s . com
    String message = "This is a INFO test";
    String tag = "my.log.info";
    Log.d(tag, message);
    Log.i(tag, message);
    Log.w(tag, message);
    List<String> list = Log.getReportedEntries();
    Assert.assertNotNull(list);
    Assert.assertFalse(list.isEmpty());
    Assert.assertEquals(2, list.size()); // i + w

    Log.report();
    Log.report("this is a user message", null);
    Exception error = new MalformedChallengeException("error message", new NumberFormatException());
    Log.report(null, error);
}

From source file:Ascii.java

public static int parseInt(char[] b, int off, int len) throws NumberFormatException {
    int c;/*  www.j a v a  2  s  .  c  om*/

    if (b == null || len <= 0 || !isDigit(c = b[off++])) {
        throw new NumberFormatException();
    }

    int n = c - '0';

    while (--len > 0) {
        if (!isDigit(c = b[off++])) {
            throw new NumberFormatException();
        }
        n = n * 10 + c - '0';
    }

    return n;
}

From source file:org.vetmeduni.tools.implemented.TrimFastq.java

@Override
protected void runThrowingExceptions(CommandLine cmd) throws Exception {
    // The input file
    File input1 = new File(getUniqueValue(cmd, "input1"));
    // input file 2
    String input2string = getUniqueValue(cmd, "input2");
    File input2 = (input2string == null) ? null : new File(input2string);
    // The output prefix
    String output_prefix = getUniqueValue(cmd, "output");
    // qualityThreshold
    int qualThreshold;
    try {//from   w w  w.j a va2  s.  c o  m
        String qualOpt = getUniqueValue(cmd, "quality-threshold");
        qualThreshold = (qualOpt == null) ? DEFAULT_QUALTITY_SCORE : Integer.parseInt(qualOpt);
        if (qualThreshold < 0) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        throw new ToolException("Quality threshold should be a positive integer");
    }
    // minimum length
    int minLength;
    try {
        String minOpt = getUniqueValue(cmd, "m");
        minLength = (minOpt == null) ? DEFAULT_MINIMUM_LENGTH : Integer.parseInt(minOpt);
        if (minLength < 1) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        throw new ToolException("Minimum length should be a positive integer");
    }
    // maximum length
    int maxLength;
    try {
        String maxOpt = getUniqueValue(cmd, "max");
        maxLength = (maxOpt == null) ? Integer.MAX_VALUE : Integer.parseInt(maxOpt);
        if (maxLength < 1) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        throw new ToolException("Maximum length should be a positive integer");
    }
    // multi-thread?
    int nThreads = CommonOptions.numberOfThreads(logger, cmd);
    boolean multi = (nThreads != 1);
    // FINISH PARSING: log the command line (not longer in the param file)
    logCmdLine(cmd);
    // save the gzip option
    boolean dgzip = CommonOptions.isZipDisable(cmd);
    // save the keep_discard option
    boolean keepDiscard = cmd.hasOption("k");
    boolean discardRemainingNs = cmd.hasOption("discard-internal-N");
    boolean trimQuality = !cmd.hasOption("no-trim-quality");
    boolean no5ptrim = cmd.hasOption("no-5p-trim");
    // save the maintained format option
    boolean isMaintained = CommonOptions.isMaintained(logger, cmd);
    // open the reader
    FastqReaderInterface reader = ToolsReadersFactory.getFastqReaderFromInputs(input1, input2, isMaintained);
    boolean single = !(reader instanceof FastqReaderPairedInterface);
    // open the writer
    ReadToolsFastqWriter writer = (keepDiscard)
            ? ToolWritersFactory.getFastqSplitWritersFromInput(output_prefix, null, dgzip, multi, single)
            : ToolWritersFactory.getSingleOrPairWriter(output_prefix, dgzip, multi, single);
    // create the trimmer
    // create the MottAlgorithm
    Trimmer trimmer = new TrimmerBuilder(single).setTrimQuality(trimQuality).setQualityThreshold(qualThreshold)
            .setMinLength(minLength).setMaxLength(maxLength).setDiscardRemainingNs(discardRemainingNs)
            .setNo5pTrimming(no5ptrim).build();
    // run it!
    process(trimmer, reader, writer, IOUtils.makeMetricsFile(output_prefix));
}

From source file:org.neo4j.server.enterprise.EnsureEnterpriseNeo4jPropertiesExist.java

@Override
protected boolean validateProperties(Properties configProperties) {
    String dbMode = configProperties.getProperty(Configurator.DB_MODE_KEY,
            EnterpriseDatabase.DatabaseMode.SINGLE.name());
    dbMode = dbMode.toUpperCase();//from   ww w  .  j  a v  a  2 s .  c om
    if (dbMode.equals(EnterpriseDatabase.DatabaseMode.SINGLE.name())) {
        return true;
    }
    if (!dbMode.equals(EnterpriseDatabase.DatabaseMode.HA.name())) {
        failureMessage = String.format("Illegal value for %s \"%s\" in %s", Configurator.DB_MODE_KEY, dbMode,
                Configurator.NEO_SERVER_CONFIG_FILE_KEY);
        return false;
    }

    String dbTuningFilename = configProperties.getProperty(Configurator.DB_TUNING_PROPERTY_FILE_KEY);
    if (dbTuningFilename == null) {
        failureMessage = String.format("High-Availability mode requires %s to be set in %s",
                Configurator.DB_TUNING_PROPERTY_FILE_KEY, Configurator.NEO_SERVER_CONFIG_FILE_KEY);
        return false;
    } else {
        File dbTuningFile = new File(dbTuningFilename);
        if (!dbTuningFile.exists()) {
            failureMessage = String.format("No database tuning file at [%s]", dbTuningFile.getAbsoluteFile());
            return false;
        } else {
            Properties dbTuning = new Properties();
            try {
                InputStream tuningStream = new FileInputStream(dbTuningFile);
                try {
                    dbTuning.load(tuningStream);
                } finally {
                    tuningStream.close();
                }
            } catch (IOException e) {
                // Shouldn't happen, we already covered those cases
                failureMessage = e.getMessage();
                return false;
            }
            String machineId = null;
            try {
                machineId = getSinglePropertyFromCandidates(dbTuning, HaSettings.server_id.name(),
                        HaConfig.CONFIG_KEY_OLD_SERVER_ID, "<not set>");
                if (Integer.parseInt(machineId) < 0) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException e) {
                failureMessage = String.format("%s in %s needs to be a non-negative integer, not %s",
                        HaSettings.server_id.name(), dbTuningFilename, machineId);
                return false;
            } catch (IllegalArgumentException e) {
                failureMessage = String.format("%s in %s", e.getMessage(), dbTuningFilename);
                return false;
            }

            String[] zkServers = null;
            try {
                zkServers = getSinglePropertyFromCandidates(dbTuning, HaSettings.coordinators.name(),
                        HaConfig.CONFIG_KEY_OLD_COORDINATORS, "").split(",");
            } catch (IllegalArgumentException e) {
                failureMessage = String.format("%s in %s", e.getMessage(), dbTuningFilename);
                return false;
            }
            if (zkServers.length <= 0) {
                failureMessage = String.format("%s in %s needs to specify at least one server",
                        HaSettings.server_id.name(), dbTuningFilename);
                return false;
            }
            for (String zk : zkServers) {
                if (!zk.contains(":")) {
                    failureMessage = String.format("Invalid server config \"%s\" for %s in %s", zk,
                            HaSettings.server_id.name(), dbTuningFilename);
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:org.apache.flink.client.cli.ProgramOptions.java

protected ProgramOptions(CommandLine line) throws CliArgsException {
    super(line);//from ww  w . j av a2 s.  c o m

    String[] args = line.hasOption(ARGS_OPTION.getOpt()) ? line.getOptionValues(ARGS_OPTION.getOpt())
            : line.getArgs();

    if (line.hasOption(JAR_OPTION.getOpt())) {
        this.jarFilePath = line.getOptionValue(JAR_OPTION.getOpt());
    } else if (args.length > 0) {
        jarFilePath = args[0];
        args = Arrays.copyOfRange(args, 1, args.length);
    } else {
        jarFilePath = null;
    }

    this.programArgs = args;

    List<URL> classpaths = new ArrayList<URL>();
    if (line.hasOption(CLASSPATH_OPTION.getOpt())) {
        for (String path : line.getOptionValues(CLASSPATH_OPTION.getOpt())) {
            try {
                classpaths.add(new URL(path));
            } catch (MalformedURLException e) {
                throw new CliArgsException("Bad syntax for classpath: " + path);
            }
        }
    }
    this.classpaths = classpaths;

    this.entryPointClass = line.hasOption(CLASS_OPTION.getOpt()) ? line.getOptionValue(CLASS_OPTION.getOpt())
            : null;

    if (line.hasOption(PARALLELISM_OPTION.getOpt())) {
        String parString = line.getOptionValue(PARALLELISM_OPTION.getOpt());
        try {
            parallelism = Integer.parseInt(parString);
            if (parallelism <= 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            throw new CliArgsException("The parallelism must be a positive number: " + parString);
        }
    } else {
        parallelism = ExecutionConfig.PARALLELISM_DEFAULT;
    }

    stdoutLogging = !line.hasOption(LOGGING_OPTION.getOpt());
    detachedMode = line.hasOption(DETACHED_OPTION.getOpt());

    if (line.hasOption(SAVEPOINT_PATH_OPTION.getOpt())) {
        String savepointPath = line.getOptionValue(SAVEPOINT_PATH_OPTION.getOpt());
        boolean allowNonRestoredState = line.hasOption(SAVEPOINT_ALLOW_NON_RESTORED_OPTION.getOpt());
        this.savepointSettings = SavepointRestoreSettings.forPath(savepointPath, allowNonRestoredState);
    } else {
        this.savepointSettings = SavepointRestoreSettings.none();
    }
}

From source file:de.akquinet.gomobile.androlog.test.MailReporterTest.java

public void testMailWithLongLog() {
    Log.init(getContext());/*ww  w  .  ja v a 2s  . co m*/
    String message = "This is a INFO test";
    String tag = "my.log.info";
    Log.d(tag, message);
    Log.i(tag, message);
    Log.w(tag, message);
    for (int i = 0; i < 200; i++) {
        Log.w("" + i);
    }
    List<String> list = Log.getReportedEntries();
    Assert.assertNotNull(list);
    Assert.assertFalse(list.isEmpty());
    Assert.assertEquals(25, list.size());

    Log.report();
    Log.report("this is a user message", null);
    Exception error = new MalformedChallengeException("error message", new NumberFormatException());
    Log.report(null, error);
}

From source file:gedi.util.MathUtils.java

/**
 * Throws an exception if n is either a real or to big to be represented by a byte.
 * @param n/*  ww  w .  ja va 2s. c o m*/
 * @return
 */
public static short shortValueExact(Number n) {
    if (n instanceof Short || n instanceof Byte)
        return n.shortValue();
    double d = n.doubleValue();
    long l = n.longValue();
    if (d == (double) l) {
        if (l >= Short.MIN_VALUE && l <= Short.MAX_VALUE)
            return (short) l;
    }
    throw new NumberFormatException();
}