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.nebulaframework.discovery.ws.colombus.ColombusServer.java

/**
 * Execution Point of Colombus Server./*from www  .  j  a v  a 2 s  .  com*/
 * 
 * @param args Command Line Arguments
 */
public static void main(String[] args) {

    // If User has given Port
    if (args.length > 0) {
        try {
            port = Integer.parseInt(args[0]);
            if (port <= 0 || port >= 65535) {
                throw new NumberFormatException("Out of Range");
            }
        } catch (NumberFormatException e) {
            showHelp();
            System.exit(1);
        }
    }

    long t1 = System.currentTimeMillis();
    log.info("[Colombus Server] Starting Up");

    // Start Web Services
    startDiscoveryService();
    startManagerService();

    log.info("[Colombus Server] Started in " + (System.currentTimeMillis() - t1) + "ms");
}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {// www . j  a  v a  2 s.c  o m
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:Main.java

public static int parseInt(char[] string, int start, int length, int radix) throws NumberFormatException {
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
        throw new NumberFormatException("Invalid radix: " + radix);
    }/*from w  ww  .  ja va 2  s.  c o m*/
    if (string == null) {
        throw new NumberFormatException(new String(string, start, length));
    }
    int i = 0;
    if (length == 0) {
        throw new NumberFormatException(new String(string, start, length));
    }
    boolean negative = string[start + i] == '-';
    if (negative && ++i == length) {
        throw new NumberFormatException(new String(string, start, length));
    }

    return parse(string, start, length, i, radix, negative);
}

From source file:Main.java

public static String binaryToRoman(int binary) {

    if (binary <= 0 || binary >= 4000) {
        throw new NumberFormatException("Value outside roman numeral range.");
    }/*  w w  w .  j  a v  a 2 s .  c o  m*/
    String roman = "";

    for (int i = 0; i < RCODE.length; i++) {
        while (binary >= BVAL[i]) {
            binary -= BVAL[i];
            roman += RCODE[i];
        }
    }
    return roman;
}

From source file:Main.java

public static int extractInt(String str) {
    Matcher matcher = Pattern.compile("\\d+").matcher(str);

    if (!matcher.find())
        throw new NumberFormatException("For input string [" + str + "]");

    return Integer.parseInt(matcher.group());
}

From source file:Main.java

public static char byte2char(byte b, boolean upper) throws NumberFormatException {
    if (b >= 0 && b <= 9) {
        return (char) (b + 0x30);
    } else if (b >= 10 && b <= 15) {
        if (upper) {
            return (char) (b + 0x37);
        } else {/*from  w w w .j  av a  2s  .  co m*/
            return (char) (b + 0x57);
        }
    }
    throw new NumberFormatException("unknown byte: " + b);
}

From source file:Main.java

public static byte[] fromb64(String str) throws NumberFormatException {
    int len = str.length();
    if (len == 0)
        throw new NumberFormatException("Empty Base64 string");

    byte[] a = new byte[len + 1];
    char c;/*from  www .  j  a  va  2  s.  co  m*/
    int i, j;

    for (i = 0; i < len; ++i) {
        c = str.charAt(i);
        try {
            for (j = 0; c != TABLE[j]; ++j)
                ;
        } catch (Exception e) {
            throw new NumberFormatException("Illegal Base64 character");
        }
        a[i] = (byte) j;
    }

    i = len - 1;
    j = len;
    try {
        while (true) {
            a[j] = a[i];
            if (--i < 0)
                break;
            a[j] |= (a[i] & 3) << 6;
            --j;
            a[j] = (byte) ((a[i] & 0x3c) >>> 2);
            if (--i < 0)
                break;
            a[j] |= (a[i] & 0xf) << 4;
            --j;
            a[j] = (byte) ((a[i] & 0x30) >>> 4);
            if (--i < 0)
                break;
            a[j] |= (a[i] << 2);

            // Nasty, evil bug in Microsloth's Java interpreter under
            // Netscape:  The following three lines of code are supposed
            // to be equivalent, but under the Windows NT VM (Netscape3.0)
            // using either of the two commented statements would cause
            // the zero to be placed in a[j] *before* decrementing j.
            // Weeeeird.
            a[j - 1] = 0;
            --j;
            // a[--j] = 0;
            // --j; a[j] = 0;

            if (--i < 0)
                break;
        }
    } catch (Exception e) {
    }

    try {
        while (a[j] == 0)
            ++j;
    } catch (Exception e) {
        return new byte[1];
    }

    byte[] result = new byte[len - j + 1];
    System.arraycopy(a, j, result, 0, len - j + 1);
    //for(i = 0; i < len - j + 1; ++i)
    //      result[i] = a[i + j];
    return result;
}

From source file:Main.java

public static Object getObject(String type, String value) throws Exception {

    type = type.toLowerCase();//from www . jav a 2  s  . c o m
    if ("boolean".equals(type))
        return Boolean.valueOf(value);
    if ("byte".equals(type))
        return Byte.valueOf(value);
    if ("short".equals(type))
        return Short.valueOf(value);
    if ("char".equals(type))
        if (value.length() != 1)
            throw new NumberFormatException("Argument is not a character!");
        else
            return Character.valueOf(value.toCharArray()[0]);
    if ("int".equals(type))
        return Integer.valueOf(value);
    if ("long".equals(type))
        return Long.valueOf(value);
    if ("float".equals(type))
        return Float.valueOf(value);
    if ("double".equals(type))
        return Double.valueOf(value);
    if ("string".equals(type))
        return value;
    else {
        Object objs[] = new String[] { value };
        return Class.forName(type).getConstructor(new Class[] { java.lang.String.class }).newInstance(objs);
    }
}

From source file:Main.java

public static Color convertHexStringToColor(String str) throws NumberFormatException {
    int multiplier = 1;
    StringTokenizer tokenizer = new StringTokenizer(str, " \t\r\n\b:;[]()+");
    while (tokenizer.hasMoreTokens()) {
        multiplier = 1;/*from  w  ww  .  ja  va2 s  . c  o  m*/
        String token = tokenizer.nextToken();
        if (null == token) {
            throw new NumberFormatException(str);
        }
        if (token.startsWith("-")) {
            multiplier = -1;
            token = token.substring(1);
        }
        int point_index = token.indexOf(".");
        if (point_index > 0) {
            token = token.substring(0, point_index);
        } else if (point_index == 0) {
            return new Color(0);
        }
        try {
            if (token.startsWith("0x")) {
                return new Color(multiplier * Integer.parseInt(token.substring(2), 16));
            } else if (token.startsWith("#")) {
                return new Color(multiplier * Integer.parseInt(token.substring(1), 16));
            } else if (token.startsWith("0") && !token.equals("0")) {
                return new Color(multiplier * Integer.parseInt(token.substring(1), 8));
            } else {
                return new Color(multiplier * Integer.parseInt(token));
            }
        } catch (NumberFormatException e) {
            continue;
        }
    }
    throw new NumberFormatException(str);

}

From source file:Main.java

/**
 * Parse an integer located between 2 given offsets in a string
 * //from   w w w  .  ja v  a2  s.  c o m
 * @param value the string to parse
 * @param beginIndex the start index for the integer in the string
 * @param endIndex the end index for the integer in the string
 * @return the int
 * @throws NumberFormatException if the value is not a number
 */
private static int parseInt(String value, int beginIndex, int endIndex) throws NumberFormatException {
    if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
        throw new NumberFormatException(value);
    }
    // use same logic as in Integer.parseInt() but less generic we're not supporting negative values
    int i = beginIndex;
    int result = 0;
    int digit;
    if (i < endIndex) {
        digit = Character.digit(value.charAt(i++), 10);
        if (digit < 0) {
            throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
        }
        result = -digit;
    }
    while (i < endIndex) {
        digit = Character.digit(value.charAt(i++), 10);
        if (digit < 0) {
            throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
        }
        result *= 10;
        result -= digit;
    }
    return -result;
}