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:configurator.Configurator.java

/**
 * Method for transform ip range like "192.168.0.1-192.168.0.254" to list of
 * ips.//from   w  ww  .  j  a  v a  2s .  c  o  m
 *
 * @param ipRange String with first and last ip
 * @return List<String> with ip addresses
 */
static List<String> parseIpRange(String ipRange) {
    List<String> ipList = new ArrayList<>();
    String ips[] = ipRange.split("-");

    if (!(validateIP(ips[0]) && validateIP(ips[1]))) {
        throw new NumberFormatException();
    }
    String[] ipOctets = ips[0].split("\\.");

    int[] ip = new int[4];
    for (int i = 0; i < 4; i++) {
        ip[i] = Integer.valueOf(ipOctets[i]);
    }

    ipList.add(ips[0]);
    while (!ips[0].equals(ips[1])) {
        ip[3]++;
        if (ip[3] == 0x100) {
            ip[3] = 0;
            ip[2]++;
        }
        if (ip[2] == 0x100) {
            ip[2] = 0;
            ip[1]++;
        }
        if (ip[1] > 254) {
            throw new NumberFormatException();
        }
        ips[0] = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];
        ipList.add(ips[0]);
    }
    return ipList;
}

From source file:za.org.opengov.ussd.service.stockout.cm.CMUssdStockoutServiceImpl.java

@Override
public CMUssdResponse createUssdResponse(CMUssdRequest request) {

    CMUssdResponse response = new CMUssdResponse();
    String displayText = "";
    String sessionId = "";
    int menuRequest = 0;

    boolean ussdEnabled = parameterService.getParam("stockout.ussd.enabled").equals("1");
    if (!ussdEnabled) {
        response.setDisplayText("This service has been disabled.");
        response.setRequestID("99");
        return response;
    }//from  www. java2  s.  c  om

    try {
        // get the stage at which the user is in,in the ussd session
        menuRequest = Integer.parseInt(request.getRequestid());
        // session id identifies session specific data stored in the key
        // value store
        sessionId = request.getUssdSessionId();

        switch (menuRequest) {

        case 0: // welcome message..clinic code prompt

            displayText = stockoutDao.getMenu(0);
            ++menuRequest;

            break;

        case 1: // validate clinic and display ussd stock out services

            displayText = request.getRequest();
            // stockoutDao.checkClinic(request.getRequest());****database
            // call

            // -----------------------------------------------------------------------------
            // String clinicName = displayText;
            // matches the best matching facility
            Facility facility = facilityService.getClosestMatch(displayText);
            // -----------------------------------------------------------------------------

            if (facility != null) {
                // Need to set clinic name so that it can be re-used later
                keyValueStore.put("facilityName." + request.getUssdSessionId(), facility);
                displayText = facility.getLocalName() + " " + facility.getFacilityType().getReadable() + " "
                        + stockoutDao.getMenu(1);
                ++menuRequest;

            } else {
                // displayed failed message and redisplay same menu
                displayText += " " + stockoutDao.getMenu(92);
                throw new NumberFormatException();
            }

            break;

        case 2: // process service request,get list of recent medicines

            displayText = stockoutDao.getMenu(91); // set error message for
            // incorrect string
            // input and invalid
            // integer selection

            int requestSelection = Integer.parseInt(request.getRequest());

            if (requestSelection >= 1 && requestSelection <= 3) {

                // -----------------------------------------------------------------------------
                int limit = 5;
                // must be facility code, not facility name
                String facilityCode = ((Facility) (keyValueStore.get("facilityName." + sessionId))).getUid();
                // facilityCode.
                List<Stockout> stockouts = stockoutService
                        .getMostCommonlyReportedStockoutsForFacility(facilityCode, limit);
                if (stockouts.size() > 0) {
                    displayText = stockoutDao.getMenu(21);
                    keyValueStore.put("commonStockouts." + sessionId, stockouts);

                    for (int index = 0; index < stockouts.size(); index++) {

                        displayText += (index + 1) + "." + stockouts.get(index).getProduct().getName() + " "
                                + stockouts.get(index).getProduct().getDescription() + "\n";
                    }
                    // or

                    // this returns most recent reports, though I could also
                    // just return most recent actual stockouts
                    // since multiple recent reports could be for same
                    // stockouts
                    // List<StockoutReport> recentReports =
                    // stockoutReportService.getRecentlyReportedStockouts(limit);

                    // -----------------------------------------------------------------------------

                    displayText += stockoutDao.getMenu(22);
                    ++menuRequest;
                } else {
                    displayText = stockoutDao.getMenu(3);
                    menuRequest += 2;

                }
                keyValueStore.put("service." + sessionId, Integer.toString(requestSelection));

            } else {

                // number greater 3 or less than 1 was chosen
                throw new NumberFormatException();
            }
            break;

        case 3: // process user selection of recent reports or manual
                // medicine name entry

            displayText = stockoutDao.getMenu(91);

            int requestMedicine = Integer.parseInt(request.getRequest());

            List<Stockout> commonStockouts = (List<Stockout>) keyValueStore.get("commonStockouts." + sessionId);

            if (requestMedicine >= 1 && requestMedicine <= 8 && commonStockouts.size() >= requestMedicine) { // process
                // medicine
                // selection
                // 1-8
                Product selectedProduct = commonStockouts.get(requestMedicine - 1).getProduct();
                if (selectedProduct != null) {

                    displayText = selectedProduct.getName() + " " + selectedProduct.getDescription();

                    //put selected product in keyvalue store
                    keyValueStore.put("productName." + sessionId, selectedProduct);
                    //get dosages for selected product
                    List<Product> productDosages = productService.getAllProductsMatchingName(selectedProduct);
                    //put dosages for selected product in key value store
                    keyValueStore.put("dosages." + sessionId, productDosages);

                    displayText += " " + stockoutDao.getMenu(4);
                    menuRequest += 3;
                } else {
                    throw new NumberFormatException();
                }

            } else if (requestMedicine == 9) { // display enter medicine
                // name prompt

                displayText = stockoutDao.getMenu(3);
                ++menuRequest;

            } else {// user enters a number less than 1 or greater than 8

                throw new NumberFormatException();

            }
            break;

        case 4: // validate/find nearest match to medicine name+display
                // appropriate menu as above

            // -----------------------------------------------------------------------------
            displayText = request.getRequest();

            Product searchProduct = productService.getClosestMatch(displayText);

            displayText = stockoutDao.getMenu(10) + " " + searchProduct.getName() + "\n";

            List<Product> productsForName = productService.getAllProductsMatchingName(searchProduct);

            for (int k = 0; k < productsForName.size(); k++) {

                displayText += (k + 1) + "." + productsForName.get(k).getDescription() + "\n";

            }

            displayText += stockoutDao.getMenu(11);

            // -----------------------------------------------------------------------------

            if ((searchProduct != null)) { // medicine name found, go
                // to next menu
                keyValueStore.put("dosages." + sessionId, productsForName);
                ++menuRequest;

            } else { // medicine name not found
                displayText += " " + stockoutDao.getMenu(92);
                throw new NumberFormatException();
            }

            break;

        case 5:

            displayText = stockoutDao.getMenu(91);

            int requestDosage = Integer.parseInt(request.getRequest());

            List<Product> productDosages = (List<Product>) keyValueStore.get("dosages." + sessionId);

            if (requestDosage >= 1 && requestDosage <= 8 && requestDosage <= productDosages.size()) {

                Product selectedProduct = productDosages.get(requestDosage - 1);
                displayText = selectedProduct.getName() + " " + selectedProduct.getDescription() + " "
                        + stockoutDao.getMenu(4);

                keyValueStore.put("productName." + sessionId, selectedProduct);
                menuRequest++;
            } else if (requestDosage == 9) {
                menuRequest = 4;
                displayText = stockoutDao.getMenu(3);
            } else {
                throw new NumberFormatException();
            }

            break;

        case 6: // run methods for each of the different services+display
                // result.

            String serviceRequest = (String) keyValueStore.get("service." + sessionId);
            Product selectedProduct = (Product) keyValueStore.get("productName." + sessionId);
            Facility selectedFacility = (Facility) keyValueStore.get("facilityName." + sessionId);

            int service = Integer.parseInt(serviceRequest);
            int requestOption = Integer.parseInt(request.getRequest());

            if (requestOption == 1) {
                switch (service) {
                case 1:
                    // StockoutDao.reportStockout(medicineName,facilityName);

                    // -----------------------------------------------------------------------------
                    // must be the correct facility and product code
                    String productCode = selectedProduct.getUid();
                    String facilityCode = selectedFacility.getUid();
                    Subject subject = new Subject();
                    subject.setContactNumber(request.getMsisdn());
                    stockoutReportService.submitStockoutReport(productCode, facilityCode, subject,
                            "stockout of product", false);
                    // -----------------------------------------------------------------------------

                    displayText = selectedProduct.getName() + " in " + selectedFacility.getLocalName() + " "
                            + selectedFacility.getFacilityType().getReadable() + " " + stockoutDao.getMenu(5);
                    break;
                case 2:
                    // displayText =
                    // StockoutDao.getStatus(MedicineName,facilityName);

                    // -----------------------------------------------------------------------------
                    // against must be proper facility code and product code
                    // (no matching is done)
                    String selectedFacilityCode = selectedFacility.getUid();
                    String selectedProductCode = selectedProduct.getUid();
                    Stockout stockout = stockoutService.getStockout(selectedFacilityCode, selectedProductCode);
                    // -----------------------------------------------------------------------------
                    if (stockout != null) {
                        displayText = stockoutDao.getMenu(6) + " " + stockout.getIssue().getState().toString()
                                + stockoutDao.getMenu(8);
                    } else {
                        displayText = stockoutDao.getMenu(62) + " " + stockoutDao.getMenu(8);
                    }
                    break;
                case 3:
                    // displayText =
                    // stockoutDao.findNearestNeighbourWithStock(medicineName,facilityName);

                    // -----------------------------------------------------------------------------
                    //System.out.println(selectedFacility.getLocalName());

                    Facility closestFacility = facilityService.getNearestFacilityWithStock(selectedProduct,
                            selectedFacility);

                    // -----------------------------------------------------------------------------

                    displayText = stockoutDao.getMenu(7) + " " + closestFacility.getLocalName() + " "
                            + closestFacility.getFacilityType().getReadable() + " " + stockoutDao.getMenu(8);
                    break;
                }

                menuRequest = 99;

            } else if (requestOption == 2) {

                displayText = stockoutDao.getMenu(10) + " " + selectedProduct.getName() + "\n";

                List<Product> productDosage = (List<Product>) keyValueStore.get("dosages." + sessionId);

                for (int k = 0; k < productDosage.size(); k++) {

                    displayText += (k + 1) + "." + productDosage.get(k).getDescription() + "\n";

                }

                displayText += stockoutDao.getMenu(11);

                // -----------------------------------------------------------------------------
                menuRequest = 5;

            } else if (requestOption == 3) {
                displayText = ((Facility) keyValueStore.get("facilityName." + sessionId)).getLocalName() + " "
                        + ((Facility) keyValueStore.get("facilityName." + sessionId)).getFacilityType()
                                .getReadable()
                        + " " + stockoutDao.getMenu(1);
                menuRequest = 2;

            } else {

                displayText = stockoutDao.getMenu(91);
                throw new NumberFormatException();
            }

            break;

        case 99:

            keyValueStore.remove("facilityName." + sessionId);
            keyValueStore.remove("service." + sessionId);
            keyValueStore.remove("productName." + sessionId);
            keyValueStore.remove("displayText." + sessionId);
            keyValueStore.remove("requestId." + sessionId);
            keyValueStore.remove("commonStockouts." + sessionId);
            keyValueStore.remove("dosages." + sessionId);

        }
    } catch (NumberFormatException e) {
        // reload data from the last request if an error in the users input
        // was detected
        // do not call setResponse as there is no need to overwrite
        // previously saved menu
        // text with the exact same text. Also avoid concatenating multiple
        // error messages

        String strMenuRequest = (String) keyValueStore.get("requestId." + sessionId);
        displayText += (String) keyValueStore.get("displayText." + sessionId);
        response.setDisplayText(displayText);
        response.setRequestID(strMenuRequest);

        return response;
    }

    // set response once menu logic processing is complete
    setResponse(response, displayText, menuRequest, sessionId);

    return response;

}

From source file:me.qcarver.wumpus.Configuration.java

/**
 * Parses command line arguments into an object. After invoking this method
 * Use getters in this class to query the values of command line arguments.
 *
 * @param args//from w w w.  j a  v a2 s .  c  o  m
 */
void parse(String[] args) {
    this.options = new Options();
    options.addOption("a", "automated", false, "automated agent");
    options.addOption("r", "arrows", true, "number of arrows in quiver, " + "default is " + arrows);
    options.addOption("b", "bumpers", true, "% chance a room is a " + "bumper room, default is " + bumpers);
    options.addOption("g", "graphic", false,
            "graphic mode, default is " + ((uiMode == UiMode.TEXT) ? "false" : "true"));
    options.addOption("d", "dimension", true,
            "the x & y dimensions of " + "the cave, default is " + gridDimension);
    options.addOption("p", "possible", false,
            "guarantee a safe path " + " to gold, default is " + (possible ? "true" : "false"));
    options.addOption("h", "help", false, "print this message");

    CommandLine cmd = null;
    Agent agent = null;
    WumpusWorld wumpusWorld = null;

    CommandLineParser parser = new BasicParser();
    try {
        cmd = parser.parse(options, args);
        help = (cmd.hasOption("h")) ? true : false;
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Wumpus World", WumpusWorld.class.getSimpleName() + " [options]", options, "",
                true);
    }
    //if isn't true by necesity.. did user request?
    if (!help) {
        uiMode = (cmd.hasOption("g") ? UiMode.GUI : UiMode.TEXT);
    }
    playMode = (cmd.hasOption("a") ? PlayMode.AUTOMATED : PlayMode.HUMAN);
    try {
        gridDimension = (cmd.hasOption("d") ? Integer.parseInt(cmd.getOptionValue("dimension"))
                : gridDimension);
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse guiDimension parameter, going " + "with default " + gridDimension);
    }
    try {
        arrows = (cmd.hasOption("r") ? Integer.parseInt(cmd.getOptionValue("arrows")) : arrows);
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse arrows parameter, going " + "with default " + arrows);
    }
    try {
        bumpers = (cmd.hasOption("b") ? Integer.parseInt(cmd.getOptionValue("bumpers")) : bumpers);
        if (bumpers > BUMPERS_MAX) {
            System.err.println("Bumpers value to high, " + "try between 0 and " + BUMPERS_MAX);
            throw new NumberFormatException();
        }
    } catch (NumberFormatException e) {
        System.err.println("Couln't parse bumpers parameter, going " + "with default " + bumpers);
    }
    possible = (cmd.hasOption("p") ? true : false);
}

From source file:services.QueryContext.java

public void setBoundingBox(String aBoundingBox) throws NumberFormatException {
    String[] coordinates = aBoundingBox.split(",");
    if (coordinates.length == 4) {
        mZoomTopLeft = new GeoPoint(Double.parseDouble(coordinates[0]), Double.parseDouble(coordinates[1]));
        mZoomBottomRight = new GeoPoint(Double.parseDouble(coordinates[2]), Double.parseDouble(coordinates[3]));
    }//from  w w w.ja v a 2 s . c o m
    throw new NumberFormatException();
}

From source file:action.ShowTimeSeriesWithForecastAction.java

/**
 * Utworz tablice liczb calkowitych (wiekszych od 0) sposrod liczb wpisanych jako ciag znakow, oddzielonych separatorem
 * /*from  w  w w . ja  v a 2 s.  com*/
 * @param str Ciag znakow
 * @return Tablica liczb calkowitych wiekszych od 0
 * @throws NumberFormatException 
 */
public int[] parseToWindowForm(String str) throws NumberFormatException {
    str = str.replaceAll(" ", "");
    str = str.replaceAll("\t", "");
    str = str.replaceAll("\n", "");
    String[] values = str.split(",");
    int[] parsed = new int[values.length];
    for (int i = 0; i < parsed.length; i++) {
        parsed[i] = Integer.valueOf(values[i]);
        if (parsed[i] <= 0)
            throw new NumberFormatException();
    }
    return parsed;
}

From source file:morphy.command.AddListCommand.java

public void process(String arguments, UserSession userSession) {

    String[] args = arguments.split(" ");
    if (args.length != 2) {
        userSession.send(getContext().getUsage());
        return;/*from   ww  w.j a va2  s  .c om*/
    }
    String listName = args[0].toLowerCase();
    String value = args[1];

    UserService us = UserService.getInstance();
    if (us.isAdmin(userSession.getUser().getUserName())) {
        ServerListManagerService serv = ServerListManagerService.getInstance();
        ServerList s = serv.getList(listName);
        if (s != null) {
            if (userSession.getUser().getUserLevel().ordinal() >= s.getPermissions().ordinal()) {
                if (s.getType().equals(ListType.Integer) && !StringUtils.isNumeric(value)) {
                    userSession.send("Bad value provided for that list (Integer required)");
                    return;
                } else if (s.getType().equals(ListType.Username) && !us.isValidUsername(value)) {
                    userSession.send("Bad value provided for that list (Username required)");
                    return;
                } else if (s.getType().equals(ListType.IPAddress)
                        && !value.matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}")) {
                    userSession.send("Bad value provided for that list (IPAddress required)");
                    return;
                } else if (s.getType().equals(ListType.String) && value.contains(" ")) {
                    userSession.send("Bad value provided for that list (String required)");
                    return;
                }

                if (listName.equals("admin") && !us.isRegistered(value)) {
                    userSession.send("Guests cannot be added to that list.");
                    return;
                }

                if (!serv.isOnList(s, value)) {
                    serv.getElements().get(s).add(value);
                    userSession.send("[" + value + "] added to the " + listName + " list.");
                    UserSession user = us.getUserSession(value);
                    if (listName.equals("admin")) {
                        user.getUser().setUserLevel(UserLevel.Admin);
                    }
                    if (listName.equals("admin") || listName.equals("sr") || listName.equals("tm")
                            || listName.equals("td") || listName.equals("computer")) {
                        if (user != null) {
                            user.send("You have been added to the " + listName + " list by "
                                    + userSession.getUser().getUserName() + ".");
                        }
                    }
                    return;
                } else {
                    userSession.send("[" + value + "] is already on the " + listName + " list.");
                    return;
                }
            } else {
                userSession.send("\"" + listName
                        + "\" is not an appropriate list name or you have insufficient rights.");
                return;
            }
        }
    }

    listName = listName.toLowerCase();
    PersonalList list = null;
    try {
        list = PersonalList.valueOf(listName);
    } catch (Exception e) {
        userSession.send("\"" + listName + "\" does not match any list name.");
        return;
    }

    List<String> myList = userSession.getUser().getLists().get(list);
    if (myList == null) {
        myList = new ArrayList<String>(User.MAX_LIST_SIZE);
        userSession.getUser().getLists().put(list, myList);
    }
    if (!myList.contains(value)) {
        if (list == PersonalList.channel) {
            ChannelService cS = ChannelService.getInstance();
            try {
                int intVal = Integer.parseInt(value);
                if (intVal < Channel.MINIMUM || intVal > Channel.MAXIMUM)
                    throw new NumberFormatException();
                Channel c = cS.getChannel(intVal);
                if (c != null)
                    c.addListener(userSession);
                else
                    userSession.send("That channel should, but does not, exist.");
            } catch (NumberFormatException e) {
                userSession.send("The channel to add must be a number between " + Channel.MINIMUM + " and "
                        + Channel.MAXIMUM + ".");
                return;
            }
        }

        if (list != PersonalList.channel) {
            String[] matches = us.completeHandle(value);
            //System.err.println(value + " " + java.util.Arrays.toString(matches));
            if (matches.length > 0) {
                if (matches.length == 1) {
                    value = matches[0];
                }
            }
        }

        myList.add(value);
        userSession.send("[" + value + "] added to your " + listName + " list.");

        int dbid = userSession.getUser().getDBID();
        boolean isGuest = dbid == 0;
        if (!isGuest) {
            DatabaseConnectionService dbcs = DatabaseConnectionService.getInstance();
            dbcs.getDBConnection().executeQueryWithRS(
                    "INSERT IGNORE INTO personallist VALUES(NULL," + dbid + ",'" + listName + "');");
            Integer listid = userSession.getUser().getPersonalListDBIDs().get(list);
            if (listid == null) {
                java.sql.ResultSet rs = dbcs.getDBConnection()
                        .executeQueryWithRS("SELECT `id`,`name` FROM personallist WHERE user_id = '" + dbid
                                + "' && name = '" + listName + "';");
                try {
                    if (rs.next()) {
                        userSession.getUser().getPersonalListDBIDs().put(PersonalList.valueOf(rs.getString(2)),
                                rs.getInt(1));
                        listid = rs.getInt(1);
                    }
                } catch (java.sql.SQLException e) {
                    Morphy.getInstance().onError(e);
                }
            }
            String query = "INSERT INTO personallist_entry VALUES(NULL," + listid + ",'" + value + "');";
            dbcs.getDBConnection().executeQuery(query);
        }
    } else {
        userSession.send("[" + value + "] is already on your " + listName + " list.");
    }
}

From source file:com.redhat.rhn.frontend.action.multiorg.SystemEntitlementOrgsAction.java

private ActionErrors updateSubscriptions(Org org, HttpServletRequest request, Entitlement ent,
        String newCount) {//from  ww  w . ja  v a2 s  .  c  om

    if (org.getId().equals(OrgFactory.getSatelliteOrg().getId())) {
        createErrorMessage(request, "org.entitlements.system.defaultorg", null);
        return null;
    }

    ActionErrors errors = new ActionErrors();

    //Validate if its a numeric value
    if (!StringUtils.isNumeric(newCount)) {
        ValidatorError error = new ValidatorError("softwareEntitlementSubs.invalidInput");
        errors.add(RhnValidationHelper.validatorErrorToActionErrors(error));
        return errors;
    }

    Long count;
    try {
        count = Long.parseLong(newCount);
        if (count < 0) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException numEx) {
        ValidatorError error = new ValidatorError("softwareEntitlementSubs.invalidInput");
        errors.add(RhnValidationHelper.validatorErrorToActionErrors(error));
        return errors;
    }

    // Store/update db
    UpdateOrgSystemEntitlementsCommand updateCmd = new UpdateOrgSystemEntitlementsCommand(ent, org, count);
    ValidatorError ve = updateCmd.store();
    if (ve != null) {
        errors.add(RhnValidationHelper.validatorErrorToActionErrors(ve));
    }

    return errors;
}

From source file:org.cimmyt.corehunter.textui.CoreanalyserTextRunner.java

private boolean parseOptions(String[] args) {
    CommandLineParser parser = new GnuParser();

    try {/*from   w  w w. j a va  2  s  .  c  o  m*/
        CommandLine cl = parser.parse(opts, args);

        // check for -help
        if (cl.hasOption("help")) {
            showUsage();
            System.exit(0);
        }

        // check for -version
        if (cl.hasOption("version")) {
            showVersion();
            System.exit(0);
        }

        // check for -precision
        if (cl.hasOption("precision")) {
            try {
                precision = Integer.parseInt(cl.getOptionValue("precision"));
                if (precision < 0 || precision > 15)
                    throw new NumberFormatException();
            } catch (NumberFormatException nfe) {
                System.err.println("\nprecision must be a positive integer value in the range [0,15]");
                return false;
            }
        }

        // make sure at least one file is specified
        if (cl.getArgs().length == 0) {
            System.err.println("\nyou must specify at least one file to analyse");
            return false;
        }

        // grab the filenames
        collectionFiles = cl.getArgs();
    } catch (ParseException e) {
        System.err.println("");
        System.err.println(e.getMessage());
        return false;
    }

    return true;
}

From source file:org.eclipse.smarthome.binding.astro.internal.util.DateTimeUtils.java

/**
 * Parses a HH:MM string and returns the minutes.
 *//*from   w  ww  .  j av a 2 s.  c  om*/
private static int getMinutesFromTime(String configTime) {
    String time = StringUtils.trimToNull(configTime);
    if (time != null) {
        try {
            if (!HHMM_PATTERN.matcher(time).matches()) {
                throw new NumberFormatException();
            } else {
                int hour = Integer.parseInt(StringUtils.substringBefore(time, ":"));
                int minutes = Integer.parseInt(StringUtils.substringAfter(time, ":"));
                return (hour * 60) + minutes;
            }
        } catch (Exception ex) {
            LOGGER.warn(
                    "Can not parse astro channel configuration '{}' to hour and minutes, use pattern hh:mm, ignoring!",
                    time);
        }
    }
    return 0;
}

From source file:com.turqmelon.MelonEco.commands.CurrencyCommand.java

@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {

    new BukkitRunnable() {
        @Override/*w ww  .  j  av a2s.co m*/
        public void run() {
            if (!sender.hasPermission("eco.currencies")) {
                sender.sendMessage("cl[Eco] cYou don't have permission to manage currencies.");
                return;
            }

            if (args.length == 0) {
                sender.sendMessage("el[Eco] eCurrency Management");
                sender.sendMessage("el[Eco] bl-> b/currency create 7<Singular> <Plural>");
                sender.sendMessage("el[Eco] bl-> b/currency delete 7<Name>");
                sender.sendMessage("el[Eco] bl-> b/currency view 7<Name>");
                sender.sendMessage("el[Eco] bl-> b/currency list");
                sender.sendMessage("el[Eco] bl-> b/currency symbol 7<Name> <Char|Remove>");
                sender.sendMessage("el[Eco] bl-> b/currency color 7<Name> <ChatColor>");
                sender.sendMessage("el[Eco] bl-> b/currency decimals 7<Name>");
                sender.sendMessage("el[Eco] bl-> b/currency payable 7<Name>");
                sender.sendMessage("el[Eco] bl-> b/currency default 7<Name>");
                sender.sendMessage("el[Eco] bl-> b/currency startingbal 7<Name> <Amount>");
            } else {
                String cmd = args[0];
                if (cmd.equalsIgnoreCase("create")) {

                    if (args.length == 3) {

                        String single = args[1];
                        String plural = args[2];

                        if (AccountManager.getCurrency(single) == null
                                && AccountManager.getCurrency(plural) == null) {

                            if (StringUtils.contains(single, ':') || StringUtils.contains(single, ',')
                                    || StringUtils.contains(plural, ':') || StringUtils.contains(plural, ',')) {
                                sender.sendMessage("cl[Eco] cInvalid character present.");
                                return;
                            }

                            Currency currency = new Currency(UUID.randomUUID(), single, plural);

                            sender.sendMessage("al[Eco] aCreated currency: " + currency.getPlural());

                            AccountManager.getCurrencies().add(currency);

                            if (AccountManager.getCurrencies().size() == 1) {
                                currency.setDefaultCurrency(true);
                            }

                            MelonEco.getDataStore().saveCurrency(currency);

                        } else {
                            sender.sendMessage("cl[Eco] cCurrency already exists.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("list")) {

                    sender.sendMessage("al[Eco] aThere are f" + AccountManager.getCurrencies().size()
                            + "a currencies.");
                    for (Currency currency : AccountManager.getCurrencies()) {
                        sender.sendMessage("al[Eco] bl-> b" + currency.getSingular());
                    }

                } else if (cmd.equalsIgnoreCase("view")) {

                    if (args.length == 2) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            sender.sendMessage("al[Eco] aInfo for " + currency.getUuid().toString());
                            sender.sendMessage("al[Eco] aSingular: f" + currency.getSingular()
                                    + "a, Plural: f" + currency.getPlural());
                            sender.sendMessage("al[Eco] aNew players start with f"
                                    + currency.format(currency.getDefaultBalance()) + "a.");
                            sender.sendMessage("al[Eco] aDecimals? f"
                                    + (currency.isDecimalSupported() ? "Yes" : "No"));
                            sender.sendMessage("al[Eco] aDefault? f"
                                    + (currency.isDefaultCurrency() ? "Yes" : "No"));
                            sender.sendMessage(
                                    "al[Eco] aPayable? f" + (currency.isPayable() ? "Yes" : "No"));
                            sender.sendMessage("al[Eco] aColor: " + currency.getColor()
                                    + currency.getColor().name());

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("startingbal")) {

                    if (args.length == 3) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            double amount;

                            if (currency.isDecimalSupported()) {
                                try {

                                    amount = Double.parseDouble(args[2]);
                                    if (amount <= 0) {
                                        throw new NumberFormatException();
                                    }

                                } catch (NumberFormatException ex) {
                                    sender.sendMessage("cl[Eco] cPlease provide a valid amount.");
                                    return;
                                }
                            } else {
                                try {

                                    amount = Integer.parseInt(args[2]);
                                    if (amount <= 0) {
                                        throw new NumberFormatException();
                                    }

                                } catch (NumberFormatException ex) {
                                    sender.sendMessage("cl[Eco] cPlease provide a valid amount.");
                                    return;
                                }
                            }

                            currency.setDefaultBalance(amount);
                            sender.sendMessage("al[Eco] aStarting balance for " + currency.getPlural()
                                    + " set: " + currency.getDefaultBalance());
                            MelonEco.getDataStore().saveCurrency(currency);

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("color")) {

                    if (args.length == 3) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            try {

                                ChatColor color = ChatColor.valueOf(args[2].toUpperCase());
                                if (color.isFormat()) {
                                    throw new Exception();
                                }

                                currency.setColor(color);
                                sender.sendMessage("al[Eco] aColor for " + currency.getPlural()
                                        + " updated: " + color + color.name());
                                MelonEco.getDataStore().saveCurrency(currency);

                            } catch (Exception ex) {
                                sender.sendMessage("cl[Eco] cInvalid chat color.");
                            }

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("symbol")) {

                    if (args.length == 3) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            String symbol = args[2];
                            if (symbol.equalsIgnoreCase("remove")) {
                                currency.setSymbol(null);
                                sender.sendMessage(
                                        "al[Eco] aCurrency symbol removed for " + currency.getPlural());
                                MelonEco.getDataStore().saveCurrency(currency);
                            } else if (symbol.length() == 1) {
                                currency.setSymbol(symbol);
                                sender.sendMessage("al[Eco] aCurrency symbol for " + currency.getPlural()
                                        + " updated: " + symbol);
                                MelonEco.getDataStore().saveCurrency(currency);
                            } else {
                                sender.sendMessage(
                                        "cl[Eco] cSymbol must be 1 character, or say \"remove\".");
                            }

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("default")) {

                    if (args.length == 2) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            Currency c = AccountManager.getDefaultCurrency();
                            if (c != null) {
                                c.setDefaultCurrency(false);
                                MelonEco.getDataStore().saveCurrency(c);
                            }

                            currency.setDefaultCurrency(true);
                            sender.sendMessage(
                                    "al[Eco] aSet default currency to " + currency.getPlural());
                            MelonEco.getDataStore().saveCurrency(currency);

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("payable")) {

                    if (args.length == 2) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            currency.setPayable(!currency.isPayable());
                            sender.sendMessage("al[Eco] aToggled payability for " + currency.getPlural()
                                    + ": " + currency.isPayable());
                            MelonEco.getDataStore().saveCurrency(currency);

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("decimals")) {

                    if (args.length == 2) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            currency.setDecimalSupported(!currency.isDecimalSupported());
                            sender.sendMessage("al[Eco] aToggled Decimal Support for "
                                    + currency.getPlural() + ": " + currency.isDecimalSupported());
                            MelonEco.getDataStore().saveCurrency(currency);

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else if (cmd.equalsIgnoreCase("delete")) {

                    if (args.length == 2) {

                        Currency currency = AccountManager.getCurrency(args[1]);
                        if (currency != null) {

                            AccountManager.getAccounts().stream()
                                    .filter(account -> account.getBalances().containsKey(currency))
                                    .forEach(account -> account.getBalances().remove(currency));

                            MelonEco.getDataStore().deleteCurrency(currency);

                            AccountManager.getCurrencies().remove(currency);

                            sender.sendMessage("al[Eco] aDeleted currency: " + currency.getPlural());

                        } else {
                            sender.sendMessage("cl[Eco] cUnknown currency.");
                        }

                    } else {
                        sender.sendMessage("cl[Eco] cUsage: f/currency create <Singular> <Plural>");
                    }

                } else {
                    sender.sendMessage("cl[Eco] cUnknown currency sub-command.");
                }
            }
        }
    }.runTaskAsynchronously(MelonEco.getInstance());

    return true;
}